While learning about objective-c. I came across a single feature of objective-c which I think if moved to c++ would make for a lot less coding.
Consider this objective c code for a class declaration:
// .h file:
@interface classname {
// instance variables
}
+(void)classMethod;
@end
// .m file:
@implementation classname
-privateFunction1{}
-classMethod { [self privateFunction1]; }
@end
While if you would have to do something similar in c++, this is how you would do it:
// .h file:
class classname
{
public:
void classMethod();
private:
void privateFunction();
}
// .cpp file:
void classname::classMethod() { privateFunction(); }
void classname::privateFunction() {}
Even if a function in a C++ class is private, you still have to declare it in the class declaration. why ?
It would be so much better if all the private functions can just placed in the cpp file, and we dont have to put them in the class declaration.
Objective C has the benefit of using @implementation … @end to figure out such methods. But if in c++ if we just declare a function in the .cpp file and such function is not present in the class declaration, the compiler can know that its a private function. Like so:
// .h file:
class sample
{
public:
void doSomething();
private:
int x;
};
// .cpp file:
void sample::doSomethingPrivately()
{
// has access to member data.
x = 7;
}
void sample::doSomething()
{
/// ...
doSomethingPrivately();
}
Robin Burchell
April 9, 2010 at 11:30 pm
There is a solution to this, known as the PIMPL pattern (amongst other things)
Basically, you declare a pointer to a seperate class, and use that to store all your data members/methods you want private/etc. Qt is one big user of this pattern.
For example:
// .h
// forward declaration
class MyFooPrivate;
class MyFoo
{
void myBar();
private:
MyFooPrivate *d_ptr;
};
// cpp
class MyFooPrivate
{
void mooCow()
{
// make a moo noise
}
};
void MyFoo::myBar()
{
d_ptr->mooCow();
// do other stuff
}
digitalSurgeon
April 13, 2010 at 9:38 am
@Robin, I am familiar with that approach ( thanks to Qt ). But I think this could be added to the next C++ language update. Do you see any thing wrong with it ? I mean not declaring private functions in the class declaration.
RFC: Improving Qt’s properties. | Technical Difficulties
July 1, 2010 at 4:40 pm
[...] look like from stone age. Objective-C has some nice features as well, one I mentioned in my previous post, which Qt already solves rather nicely and in a better way as one of the commenter pointed out. [...]