Evan Ward
Evan Ward

Reputation: 1419

C++ - Constructors calling constructors

I'm not sure how to phrase this or what it's actually called, but I know that in Objective-C you can have multiple constructors that can successively call one another, forgive any code erros, I haven't done this in a while, but the idea is there.

- (id)initWithTitle:(NSString *)_title;
- (id)initWithTitle:(NSString *)_title page:(NSString *)_page;

-----------------------------------

- (id)initWithTitle:(NSString *)_title {
    return [self initWithTitle:_title page:nil];
}

- (id)initWithTitle:(NSString *)_title page:(NSString *)_page {
    if(self = [super init]) {
        self.title = _title;
        self.page = _page;
    }
    return self;
}

I'm just wondering if there is an equivalent of this in c++;

Upvotes: 3

Views: 197

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254431

In C++11, you can delegate to other constructors:

Thing(string title) : title(title) {}
Thing(string title, string page) : Thing(title) {this->page = page;}

Historically, you could perform the shared work in a function:

Thing(string title) {init(title);}
Thing(string title, string page) {init(title); this->page = page;}

although, in a simple case like this, you'd probably be better off with a default argument

Thing(string title, string page = "") : title(title), page(page) {}

Upvotes: 4

user2026095
user2026095

Reputation:

In C++ 11 you have Delegating constructors: https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/introduction_to_the_c_11_feature_delegating_constructors?lang=en

Pre C++11 there is no way for one constructor to call the other. In this case either use copy/paste or a a single method that initializes all the variables, and is called from multiple constructors.

Upvotes: 2

Sean
Sean

Reputation: 62472

Prior to C++11 you couldn't do this, but as of C++11 you can

class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //new to c++11
};

Upvotes: 5

Related Questions