473,387 Members | 1,897 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

what happens if i call a base class virtual function in a derived class constructor?

what happens if i call a base class virtual function in a derived class constructor?
Oct 26 '10 #1
2 1792
When constructing the derived class, the base class is constructed first. If you call a virtual method from the base class constructor, the overridden method is called. But notice that when that overridden method is called, the derived class is not initialized because its constructor code was not executed yet.
Oct 29 '10 #2
Banfa
9,065 Expert Mod 8TB
If you call a virtual function from a base class then you will call the function in the base class because the vtable is filled in as the class hierarchy is constructed and that is constructed from base class to derived class.

This code demonstrates that

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include<iostream>
  3. using namespace std;
  4.  
  5.  
  6. class Base
  7. {
  8. public:
  9.     Base()
  10.     {
  11.         print();
  12.     }
  13.  
  14.     ~Base()
  15.     {
  16.     }
  17.  
  18.     virtual void print()
  19.     {
  20.         cout << "Base : " << name() << endl;
  21.     }
  22.  
  23.     virtual const char *name()
  24.     {
  25.         return "Base";
  26.     }
  27. };
  28.  
  29. class Derived : public Base
  30. {
  31. public:
  32.     Derived()
  33.     {
  34.         print();
  35.     }
  36.  
  37.     ~Derived()
  38.     {
  39.     }
  40.  
  41.     virtual void print()
  42.     {
  43.         cout << "Derived : " << name() << endl;
  44.     }
  45. };
  46.  
  47. class MoreDerived : public Derived
  48. {
  49. public:
  50.     MoreDerived()
  51.     {
  52.         print();
  53.     }
  54.  
  55.     ~MoreDerived()
  56.     {
  57.     }
  58.  
  59.     virtual void print()
  60.     {
  61.         cout << "MoreDerived : " << name() << endl;
  62.     }
  63.  
  64.     virtual const char *name()
  65.     {
  66.         return "MoreDerived";
  67.     }
  68. };
  69.  
  70.  
  71. int main()
  72. {
  73.     MoreDerived md;
  74.     return 0;
  75. }
  76.  
showing that as MoreDerived goes though the stages of constructing Base then Derived then MoreDerived caused by the instantiation in main, it calls virtual functions from each of the classes in question as the class is built up from its inherited components giving the output

Expand|Select|Wrap|Line Numbers
  1. Base : Base
  2. Derived : Base
  3. MoreDerived : MoreDerived
  4.  
So when calling a virtual function from a base constructor it is using the base classes vtable and calls the base method not the method of the class being constructed.

So this means that if you call a virtual function from a constructor the intended function call may not take place if the class is used as a base for another class.

Worst still if the function is pure virtual in the class calling it then you will dereference a NULL pointer and cause a crash which can be demonstrated by changing Base in my example to

Expand|Select|Wrap|Line Numbers
  1. class Base
  2. {
  3. public:
  4.     Base()
  5.     {
  6.         print();
  7.     }
  8.  
  9.     ~Base()
  10.     {
  11.     }
  12.  
  13.     virtual void print()
  14.     {
  15.         cout << "Base : " << name() << endl;
  16.     }
  17.  
  18.     virtual const char *name() = 0;
  19. };
  20.  
giving the output

Expand|Select|Wrap|Line Numbers
  1. pure virtual method called
  2. terminate called without an active exception
  3. Aborted
  4.  
You can never be absolutely sure someone wont derive from your class so ...

For these reasons calling a virtual function from a constructor is considered bad practice and calling one from a destructor is generally worst.

Your compiler may be able to warn you about this and static analysis tools like lint certainly can.
Oct 29 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Sridhar R | last post by:
Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this...
8
by: Webster | last post by:
Hello, I have a class Shape and subclasses Circle, Rectangle etc. I also have a function to write them to a file given a filepointer. However, I store the colour info in the Shape class. My...
2
by: Xiangliang Meng | last post by:
Hi, all. What will happen if a virtual function is declared to be virtual again in a derived class? Any harm? Best Regards, Xiangliang Meng
9
by: Daniel Kay | last post by:
Hello! I have written two template classes which implement the observerpattern in C++. I hope I manage to desribe the problem I have. template<class T> class Observer { /* ... */ }; ...
3
by: J.J. Feminella | last post by:
(Please disregard the previous message; I accidentally sent it before it was completed.) I have source code similar to the following. public class Vehicle { protected string dataV; // ......
7
by: Baski | last post by:
Base class: class AssetBase { string _clli; public string CLLI { get
1
by: Mark McDonald | last post by:
This question kind of follows on from Mike Spass’ posting 10/11/2004; I don’t understand why you can’t declare an implicit operator to convert a base class to a derived class. The text...
6
by: Hubert Fritz | last post by:
Hello, I fear I want to have something which is not possible in C++. How is it possible to define a base class so that the derived class is forced to contain a static member variable, which...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.