Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ scope operator grouping?

Is there a way to group methods scoped to a specific class, without using the scoping operator :: every time? At risk of arousing contempt in some, I can make a rough analogy to the JavaScript with statement; however, here it is used in the source, and not executed.

A simplified example: imagine a Cheese class, with the weigh, shred, and melt functions declared as follows:

class Cheese {
    public:
        Cheese();
        ... // other constructors, copy, etc.
        ~Cheese();
        int weigh();
        int shred();
        int melt();
}

Typically the functions definitions are as follows:

Cheese::Cheese() { //constructor stuff };
... // other constructors, copy, etc.
Cheese::~Cheese() { //destructor stuff };
int Cheese::weigh() { return weighed; }
int Cheese::shred() { return shredded; }
int Cheese::melt() { return melted; }

Is there a way to say, "Hey compiler, all these definitions are scoped to the Cheese class."

Perhaps like so?

scope::Cheese {
    Cheese() { //constructor stuff };
    ... // other constructors, copy, etc.
    ~Cheese() { //destructor stuff };
    int weigh() { return weighed; }
    int shred() { return shredded; }
    int melt() { return melted; }
}

or,

Cheese:: {
    Cheese() { //constructor stuff };
    ... // other constructors, copy, etc.
    ~Cheese() { //destructor stuff };
    int weigh() { return weighed; }
    int shred() { return shredded; }
    int melt() { return melted; }
}
like image 462
kmiklas Avatar asked Dec 27 '25 16:12

kmiklas


1 Answers

Other than defining the methods in the function definition block itself (which has various potential disadvantages), no, there is not any way to do this.

At least part of the reason for this is to ensure that classes, unlike namespaces, cannot be "re-opened" to have additional members added.

like image 60
Kyle Strand Avatar answered Dec 30 '25 05:12

Kyle Strand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!