Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ virtual function from constructor [duplicate]

Why the following example prints "0" and what must change for it to print "1" as I expected ?

#include <iostream> struct base {    virtual const int value() const {       return 0;    }    base() {       std::cout << value() << std::endl;    }    virtual ~base() {} };  struct derived : public base {    virtual const int value() const {       return 1;    } };  int main(void) {    derived example; } 
like image 621
Giovanni Funchal Avatar asked Jan 30 '09 17:01

Giovanni Funchal


People also ask

Can I call a virtual function from constructor?

You can call a virtual function in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, “base before derived”.

What is a copy constructor can we call a virtual function from a constructor?

A copy constructor is a special type of constructor that is used to create an object that is an exact copy of the object that is passed. A virtual function is a member function that is declared in the parent class and is redefined ( overridden) in a child class that inherits the parent class.

Why is it not acceptable to call a virtual method from the constructor of an abstract class?

Technically it is possible, but it won't work as you expect, so don't do it, because the virtual table for derived classes has not been constructed yet.

Which prototype can be a copy constructor of class Hello?

A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype: ClassName (const ClassName &old_obj);


2 Answers

Because base is constructed first and hasn't "matured" into a derived yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized.

like image 67
Sean Bright Avatar answered Oct 07 '22 11:10

Sean Bright


When a derived object is being constructed, before the body of the derived class constructor is called the base class constructor must complete. Before the derived class constructor is called the dynamic type of the object under construction is a base class instance and not a derived class instance. For this reason, when you call a virtual function from a constructor, only the base class virtual function overrides can be called.

like image 35
CB Bailey Avatar answered Oct 07 '22 10:10

CB Bailey