Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;

like image 686
Evan Ward Avatar asked Sep 24 '26 21:09

Evan Ward


1 Answers

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
};
like image 182
Sean Avatar answered Sep 27 '26 10:09

Sean