Virtual methods & overriding in C++

A few months ago my friend asked me if I could explain a virtual methods in C++. How to use them, how to implement and why are these so important when programming?

Today I am going to answer all of these questions. First of all, we use virtual methods during inheritance. We create a pointer of base class type, but it is a pointer to our inheriting class. As you can guess, if there are only normal (not virtual) methods, when we create object of our inheriting class type, it would have only methods from a base class, not from its own. In situations like this we have to override methods from a base class – and we use a virtual methods.

We can create a base class, which has only virtual methods – we name it abstract class – or with normal & virtual. If you create a class with virtual methods, it is nice to create a virtual destructor.

Let’s start with a short example written in C++

#include <iostream>

using namespace std;

class CBook      //our base class
 CBook(){};     // default constructor
 CBook(int cost); // another constructor
 virtual ~CBook(){} // destructor(remember - virtual)
 virtual void SetTitle() { cout << "Just a book" << endl; } //virtual method which we are going to override
 /*int GetCost() { cout << itsCost << endl; } //accessor
 void SetCost(int cost) { itsCost = cost; } //mutator*/
/*protected: //protected, because it would be only visible to a base and inheriting classes
 int itsCost;*/

class CCrimeBook : public CBook
 virtual ~CCrimeBook(){}
 void SetTitle() { cout << "Crime book" << endl; } //here we override method from a base class

 CBook::CBook(int cost) : itsCost(cost){}
 int _tmain(int argc, _TCHAR* argv[])
 CBook *pBook; //here we create a pointer of a base class type

 int choice;
 bool quit;
 quit = false;

 cin >> choice;
 case 1:
 pBook = new CBook(); //we assign a new object of CBook to our pointer
 pBook->SetTitle(); //setting and getting title
 case 2:
 pBook = new CCrimeBook; //we assign a new object of CCrimeBook to our pointer
 pBook->SetTitle();//setting and getting title
 quit = true;
 return 0;

I hope that it is helpful and useful. Example of working appclication below.

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:


Komentujesz korzystając z konta Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )


Connecting to %s