Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not calling base class constructor from derived class

Say I have a base class:

class baseClass  
{  
  public:  
baseClass() { };

};

And a derived class:

class derClass : public baseClass
    {  
      public:  
    derClass() { };

    };

When I create an instance of derClass the constructor of baseClass is called. How can I prevent this?

like image 480
Brad Avatar asked Oct 31 '10 21:10

Brad


People also ask

How do you call a base class constructor from a derived class?

How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++

Can a child class call the constructor of a base class?

In Inheritance, the child class acquires the properties of the base class or parent class. You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript.

Does derived class inherit base class constructor?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.

How do you call a base class constructor from a derived class in Python?

Use super(). __init__() to call the immediate parent class constructor. Call super(). __init__(args) within the child class to call the constructor of the immediate parent class with the arguments args .


1 Answers

Make an additional empty constructor.

struct noprapere_tag {};

class baseClass  
{  
public:  
  baseClass() : x (5), y(6) { };

  baseClass(noprapere_tag) { }; // nothing to do

protected:
  int x;
  int y;

};

class derClass : public baseClass
{  
public:  
    derClass() : baseClass (noprapere_tag) { };

};
like image 87
Alexey Malistov Avatar answered Oct 16 '22 01:10

Alexey Malistov