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();
}