MoA
MoA

Reputation: 11

c++ Is it possible to create a constructor in a derived class that is not based on its base class?

Executing the code below will give an error to the line Child(){/**........code*/} saying: no matching function for call to 'Base::Base()' and that canditate Base::Base(int) expects 1 argument, and none is provided.

class Base
{

public:
    Base(int test)
    {

    };

};

class Child : public Base
{

public:
    Child ()
    {
        /**....
           ....
           code*/
    };
    Child(int test):Base(test)
    {

    };
};

So I would like to know if there is a way to use a constructor in the derived class - for example: Child(){}; - that doesn't have any association with its base class.

Upvotes: 1

Views: 72

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

No.

By your definition a Child inherits from Base and it is not possible to create a Child without the Base subobject.

Instead you should provide an argument (whatever is a good default):

Child() : Base(42) {};

Alternatively Base could provide a default constructor (one that can be called without arguments), that would be

class Base {
public:
    Base(int test = 42) {};    
};

then your Child would be ok as is.

Upvotes: 5

Tanveer Badar
Tanveer Badar

Reputation: 5523

You still need to call the user defined constructor. You can however pass a dummy argument to it if your application will tolerate that. Otherwise, it is bad application design and something will break somewhere later on.

class Child : public Base
{

public:
    Child ()
         : Base(0)
    {
        /**....
           ....
           code*/
    };
    Child(int test):Base(test)
    {

    };
};

Upvotes: 0

Related Questions