Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Instantiating derived class and using base class's constructor

I have a base class with a constructor that requires one parameter (string). Then I have a derived class which also has its' own constructor. I want to instantiate the derived class and be able to set the parameter of the base class's constructor as well.

class BaseClass {
    public:
        BaseClass (string a);
};

class DerivedClass : public BaseClass {
    public:
        DerivedClass (string b);
};

int main() {
    DerivedClass abc ("Hello");
}

I'm not sure how to set the base class constructor's parameter when calling the derived class.

like image 483
yeenow123 Avatar asked Aug 20 '12 21:08

yeenow123


2 Answers

You have two possibilities - inline:

class DerivedClass : public BaseClass {
public:
    DerivedClass (string b) : BaseClass(b) {}
};

or out of line:

class DerivedClass : public BaseClass {
public:
    DerivedClass (string b);
};

/* ... */
DerivedClass::DerivedClass(string b) : BaseClass(b)
{}

more examples:

class DerivedClass : public BaseClass {
public:
    DerivedClass(int a, string b, string c);

private:
    int x;
};

DerivedClass::DerivedClass(int a, string b, string c) : BaseClass(b + c), x(a)
{}

on initializer lists:

class MyType {
public:
    MyType(int val) { myVal = val; }    // needs int
private:
    int myVal;
};

class DerivedClass : public BaseClass {
public:
    DerivedClass(int a, string b) : BaseClass(b)
    {  x = a;  }   // error, this tries to assign 'a' to default-constructed 'x'
                   // but MyType doesn't have default constructor

    DerivedClass(int a, string b) : BaseClass(b), x(a)
    {}             // this is the way to do it
private:
    MyType x;
};
like image 139
Fiktik Avatar answered Oct 22 '22 07:10

Fiktik


If all you want to do is construct a derived class instance from a single parameter that you pass to the base class constructor, you can to this:

C++03 (I have added explicit, and pass by const reference):

class DerivedClass : public BaseClass {
    public:
        explicit DerivedClass (const std::string& b) : BaseClass(b) {}
};

C++11 (gets all the base class constructors):

class DerivedClass : public BaseClass {
public:
    using BaseClass::BaseClass;
};

If you want to call different DerivedClass constructors and call the BaseClass constructor to some other value, you can do it too:

class DerivedClass : public BaseClass {
    public:
        explicit DerivedClass () : BaseClass("Hello, World!") {}
};
like image 3
juanchopanza Avatar answered Oct 22 '22 08:10

juanchopanza