Home > Software design >  Can you define C methods in a reopened class environment, rather than by prefixing with the class
Can you define C methods in a reopened class environment, rather than by prefixing with the class

Time:01-15

In every lesson and book on C I've ever seen, a class has been written like this:

header.h

class MyClass
{
   ...
   int myMethod(int my_para);
};

source.cpp

...
int
MyClass::myMethod(int my_para)
{
   ...
}

But I do find that the MyClass:: just adds to the natural chaos and bewilderment of C , especially when MyClass is actually more like MySomethingSomethingCreator. I would like to write my class definitions in more of a namespace style, like this:

header.h

class MyClass
{
   ...
   int myMethod(int my_para);
};

source.cpp

class MyClass
{
   ...
   int myMethod(int my_para)
   {
      ...
   }
}

Now, I know from trying that doing exactly this does not work, but is there a way to do something similar - just to remove a little of the noise? I am not interested in defining functions actually inside the class declaration - that's the work of the devil!

CodePudding user response:

but is there a way to do something similar

No.

MyClass:: just adds to the natural chaos and bewilderment of C

It's just one of the little things that a new C programmer has to learn to accept. Once you get used to it, it will no longer be bewildering.

CodePudding user response:

MyClass:: just adds to the natural chaos and bewilderment of C

I wouldn't agree with you. Imagine you are working with a huge code database, and you come across a definition of a function in .cpp file like this.

.
.
.
.
    int myfunc(std::string some_arg)
    {
        //whatever can be here    
    }
.
.
.
.
.

And now you would wonder, is this a function in a namespace or method of some class. Of course the class specifier you suggested would appear above, but in can be thousand of lines above, or even 10 thousands, which one probably wouldn't want to deal with. Someone would like to know if it is a method or function by directly looking on it.

The MyClass:: specifier serves greatly for this purpose.

  •  Tags:  
  • Related