Click here to Skip to main content
11,578,524 members (61,555 online)
Click here to Skip to main content

Think before you code, Virtual Functions in C++

, 2 Sep 2008 CPOL 59.3K 139
Rate this:
Please Sign up or sign in to vote.
Virtual functions in C++.

Introduction

A few days back, I was doing a job, and unintentionally, I made a mistake in the code (What mistake? That I will explain in the detailed section of the article), and when I was caught by a bug and started de-bugging it, I was amazed how a little mistake can give a programmer a whole lot of pain. Yes, I made a mistake in the virtual function area. How? Let's find out........

Using the code

So, why do we need a virtual function? Everyone knows that. Let's say I have a base class and a few derived class as well; and all the derived classes shares a common function, and in the driver program, I do not want to make a big huge switch/if block. I want to iterate through all the derived types and want to execute the common member function. Like this:

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
class CommunicationDevices
{
 //Base class has some property, for this article I dont need those
 public:
   inline virtual void which(){
     cout<<"This is a common device..."<<endl;
   }
};

class MobilePhoneWithGSMSupport:public CommunicationDevices
{
  //Derived class also has some extended property, GSM related
  public:
    inline virtual void which(){
     cout<<"This is a Mobile Phone...GSM Supported"<<endl;
    }
};

class MobilePhoneWithCDMASupport:public CommunicationDevices
{
  //Derived class also has some extended property, CDMA related
  public:
    inline void which(){
      cout<<"This is a Mobile Phone....CDMA Supported"<<endl;
    }
};

class Landline:public CommunicationDevices
{
  //Derived class also has some extended property
  public:
    inline void which(){
      cout<<"This is a Landline Phone..."<<endl;
    }
};

class Iphone:public MobilePhoneWithGSMSupport
{
  //More specific IPhone Feature here
  public:
    inline void which(){
      cout<<"This is apple Iphone with AT&T connection, GSM Support only..."
          <<endl;
    }
};


void whichPhoneUserIsUsing(CommunicationDevices &devices){
  devices.which();
}

int main(){
 MobilePhoneWithGSMSupport user1;
 MobilePhoneWithCDMASupport user2;
 Landline user3;
 Iphone user4;
 whichPhoneUserIsUsing(user1);
 whichPhoneUserIsUsing(user2);
 whichPhoneUserIsUsing(user3);
 whichPhoneUserIsUsing(user4);
 return 0;
}

Here, the idea is simple. Since we are using a virtual function in the base class, the “whichPhoneUserIsUsing()” method can take a generic base class argument, and the proper method from the derived class gets accessed depending upon the actual type of the object. This is the beauty of virtual functions. Note that in the method “whichPhoneUserIsUsing()”, we used a reference to the base class as the argument: “CommunicationDevices &devices”, and from the driver (main()), we are passing the derived class' object while calling this function. This is normally called as Upcasting in C++. That is, we are going from the more specific type to the more generic type. And, this casting is type-safe always. As you expected, this code will produce the following o/p:

bash-3.2$ g++ -g -o hello code1.cpp

bash-3.2$ ./hello

This is a Mobile Phone...GSM Supported
This is a Mobile Phone....CDMA Supported
This is a Landline Phone...
This is apple Iphone with AT&T connection, GSM Support only...

Now, consider the following code, only a single character (believe me, just a single character) has been changed here from the previous code:

We just modified our method whichPhoneUserIsUsing() like this:

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
class CommunicationDevices
{
 //Base class has some property, for this article I dont need those
 public:
   inline virtual void which(){
     cout<<"This is a common device..."<<endl;
   }
};

class MobilePhoneWithGSMSupport:public CommunicationDevices
{
  //Derived class also has some extended property, GSM related
  public:
    inline virtual void which(){
     cout<<"This is a Mobile Phone...GSM Supported"<<endl;
    }
};

class MobilePhoneWithCDMASupport:public CommunicationDevices
{
  //Derived class also has some extended property, CDMA related
  public:
    inline void which(){
      cout<<"This is a Mobile Phone....CDMA Supported"<<endl;
    }
};

class Landline:public CommunicationDevices
{
  //Derived class also has some extended property
  public:
    inline void which(){
      cout<<"This is a Landline Phone..."<<endl;
    }
};

class Iphone:public MobilePhoneWithGSMSupport
{
  //More specific IPhone Feature here
  public:
    inline void which(){
      cout<<"This is apple Iphone with AT&T connection, GSM Support only..."
          <<endl;
    }
};


void whichPhoneUserIsUsing(CommunicationDevices devices){
  devices.which();
}

int main(){
 MobilePhoneWithGSMSupport user1;
 MobilePhoneWithCDMASupport user2;
 Landline user3;
 Iphone user4;
 whichPhoneUserIsUsing(user1);
 whichPhoneUserIsUsing(user2);
 whichPhoneUserIsUsing(user3);
 whichPhoneUserIsUsing(user4);
 return 0;
}

We just modified our method whichPhoneUserIsUsing() like this:

void whichPhoneUserIsUsing(CommunicationDevices devices){

 devices.which();

}

and bang.................given below is the output:

bash-3.2$ g++ -g -o hello code2.cpp 

bash-3.2$ ./hello

This is a common device...
This is a common device...
This is a common device...
This is a common device...

bash-3.2$ vim code2.cpp

So, what gets wrong here?

Yes, you guessed it correctly, it's a famous copy-constructor problem. When the arguments are just a “CommunicationDevices” instead of a reference to it, the function says:

Hey Mr. Programmer, I am bound to create only a temporary object for this function (whichPhoneUserIsUsing()). I am no more responsible to take a reference, so I don't care what kind of actual object you are passing through; I will create a concrete “CommunicationDevices” object, and will copy only those segments from the actual object which are meaningful to me (i.e., which are part of the base class). And, will only invoke the “which” method for this temporary object. And hence, every time you call me, I will call the base class version (i.e., CommunicationDevices version) of the which() method.

This famous property is called Object Bisection, or Object Slicing. Cutting down the desired property from one object and copying it to a concrete base class object.

References:

  1. C++ Programming Language: Bjarne Stroustrup

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

programmersmind
Software Developer (Senior) Rebaca Technologies
India India
int main(){
while(!isSleeping())
{
write_code();
}
return 0;
}

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 3 Pin
ALOK KUMAR7-Feb-13 19:27
memberALOK KUMAR7-Feb-13 19:27 
GeneralNot about virtual functions at all Pin
xawari15-Jun-12 2:40
memberxawari15-Jun-12 2:40 
QuestionNicely explained, its all about style Pin
Rahul Rajat Singh16-Feb-12 1:14
memberRahul Rajat Singh16-Feb-12 1:14 
QuestionI don`t know why a C++ programer always forget to use pointer or reference to imply dynamic function? Pin
Carlos_never24-Sep-10 16:10
memberCarlos_never24-Sep-10 16:10 
GeneralSurprise?! Pin
rerser gfdg29-Jul-09 7:08
memberrerser gfdg29-Jul-09 7:08 
GeneralGood find Pin
Donsw5-Jun-09 1:45
memberDonsw5-Jun-09 1:45 
GeneralVery Good Pin
Akram Ben Hassan27-Apr-09 16:40
memberAkram Ben Hassan27-Apr-09 16:40 
GeneralMake them const Pin
Stephen Adrian Hill8-Sep-08 22:57
memberStephen Adrian Hill8-Sep-08 22:57 
GeneralAdvanced OOP Pin
sickfile8-Sep-08 21:32
membersickfile8-Sep-08 21:32 
Generalrefactor base code Pin
Casey Shaar8-Sep-08 11:48
memberCasey Shaar8-Sep-08 11:48 
Generalchange your habits Pin
J0ker7-Sep-08 17:25
memberJ0ker7-Sep-08 17:25 
GeneralRe: change your habits Pin
programmersmind8-Sep-08 8:44
memberprogrammersmind8-Sep-08 8:44 
GeneralRe: change your habits Pin
Damir Valiulin8-Sep-08 10:19
memberDamir Valiulin8-Sep-08 10:19 
GeneralRe: change your habits Pin
J0ker11-Sep-08 17:49
memberJ0ker11-Sep-08 17:49 
GeneralRe: change your habits Pin
T-Mac-Oz9-Sep-08 13:43
memberT-Mac-Oz9-Sep-08 13:43 
GeneralRe: change your habits Pin
T-Mac-Oz9-Sep-08 13:29
memberT-Mac-Oz9-Sep-08 13:29 
GeneralRe: change your habits Pin
J0ker11-Sep-08 7:50
memberJ0ker11-Sep-08 7:50 
GeneralRe: change your habits [modified] Pin
T-Mac-Oz11-Sep-08 13:00
memberT-Mac-Oz11-Sep-08 13:00 
GeneralRe: change your habits Pin
J0ker11-Sep-08 17:37
memberJ0ker11-Sep-08 17:37 
GeneralRe: change your habits Pin
T-Mac-Oz11-Sep-08 18:42
memberT-Mac-Oz11-Sep-08 18:42 
GeneralRe: change your habits Pin
J0ker12-Sep-08 1:58
memberJ0ker12-Sep-08 1:58 
GeneralNice One Pin
ioeilsk5-Sep-08 9:33
memberioeilsk5-Sep-08 9:33 
GeneralRe: Nice One Pin
programmersmind11-Sep-08 4:09
memberprogrammersmind11-Sep-08 4:09 
GeneralC++ Gotchas vs Lippman and Meyers Pin
pg--az2-Sep-08 18:32
memberpg--az2-Sep-08 18:32 
GeneralA few words..... [modified] Pin
Dezhi Zhao2-Sep-08 11:57
memberDezhi Zhao2-Sep-08 11:57 
GeneralRe: A few words..... Pin
programmersmind3-Sep-08 11:32
memberprogrammersmind3-Sep-08 11:32 
GeneralRe: A few words..... Pin
Dezhi Zhao3-Sep-08 18:02
memberDezhi Zhao3-Sep-08 18:02 
GeneralRe: A few words..... Pin
Craig Atwood9-Sep-08 1:16
memberCraig Atwood9-Sep-08 1:16 
GeneralRe: A few words..... Pin
Leblanc Meneses8-Sep-08 7:02
memberLeblanc Meneses8-Sep-08 7:02 
GeneralRe: A few words..... Pin
Rob Grainger22-Apr-10 1:55
memberRob Grainger22-Apr-10 1:55 
GeneralRe: A few words..... Pin
Dezhi Zhao26-Apr-10 10:17
memberDezhi Zhao26-Apr-10 10:17 
QuestionAnother misatake through inline? Pin
mdd2-Sep-08 9:33
membermdd2-Sep-08 9:33 
AnswerRe: Another misatake through inline? Pin
programmersmind2-Sep-08 9:43
memberprogrammersmind2-Sep-08 9:43 
GeneralRe: Another misatake through inline? Pin
T-Mac-Oz9-Sep-08 12:47
memberT-Mac-Oz9-Sep-08 12:47 
GeneralRe: Another misatake through inline? Pin
J0ker11-Sep-08 18:00
memberJ0ker11-Sep-08 18:00 
GeneralRe: Another misatake through inline? Pin
T-Mac-Oz11-Sep-08 18:57
memberT-Mac-Oz11-Sep-08 18:57 
GeneralRe: Another misatake through inline? Pin
J0ker11-Sep-08 18:09
memberJ0ker11-Sep-08 18:09 
GeneralRe: Another misatake through inline? Pin
T-Mac-Oz11-Sep-08 19:11
memberT-Mac-Oz11-Sep-08 19:11 
GeneralRe: Another misatake through inline? [modified] Pin
J0ker12-Sep-08 0:29
memberJ0ker12-Sep-08 0:29 
GeneralThanks for sharing your experience Pin
leopwkel2-Sep-08 9:10
memberleopwkel2-Sep-08 9:10 
GeneralOnly one word ......Excellent !!!! Pin
qweew2-Sep-08 9:07
memberqweew2-Sep-08 9:07 
Generalprogrammersmind ====&gt; Nice Article Pin
cijeilla2-Sep-08 8:56
membercijeilla2-Sep-08 8:56 
GeneralRe: programmersmind ====&gt; Nice Article Pin
programmersmind2-Sep-08 9:14
memberprogrammersmind2-Sep-08 9:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 2 Sep 2008
Article Copyright 2008 by programmersmind
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid