Question

Is there a way to use "block" class scope resolution in C++ so that I don't have to write the same boilerplate code for every function in my class' implementation file.

I find it extremely repetitive to write the same class name and binary scope resolution operator (Classname::) when defining a function outside of the header file in C++.

In Objective-C I only need to include functions within the @implementation/@end block.

Objective-C Example:

// Buttons.h
@interface Buttons : UIView {
    NSMutableArray *buttonArray;
}
- (int)getNumberButtons;

// Buttons.m
#import "Buttons.h"
@implementation 
- (int)getNumberButtons 
{
    return [buttonArray count];
}
@end // End implemenation

C++ Example

// Buttons.h
class Buttons {
public:
    int getNumberOfButtons() const;
protected:
    std::vector<Button> buttons;
};
// Buttons.cpp
#include "Buttons.h"
int Buttons::getNumberOfButtons() const {
    return buttons.size();
}
Was it helpful?

Solution

No, unless you would implement it all in the header in the class definition (which you usually shouldn't).

Technically you could hack it with macros, but everyone else looking at the code would hate you for it. You'll have to get used to "the C++ way" here.

Depending on what IDE you work with, there are usually tools (e.g. Visual Assist X for Visual Studio) that help you generate some of the boilerplate from a class definition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top