Virtual Class in C++

Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances.

Why we need Virtual Class :

the situation where we have one class A .This class is A is inherited by two other classes B and C. Both these class are inherited into another in a new class D

Class A -> B & C
B & C -> D

So data members/function of class A are inherited twice to class D. One through class B and second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to which data/function member would be called? One inherited through B or the other inherited through C. This confuses compiler and it displays error.

Lets See an example :
                   #include < iostream> 
                   using namespace std; 
                      
                    class A { 
                    public: 
                        void show() 
                        { 
                            cout << "Hello form A \n"; 
                        } 
                    }; 
                      
                    class B : public A { 
                    }; 
                      
                    class C : public A { 
                    }; 
                      
                    class D : public B, public C { 
                    }; 
                      
                    int main() 
                    { 
                        D object; 
                        object.show(); 
                    } 
                
Output :
                    Compiler will get confuse and will throw ambiguity error . 
                

To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual base class by placing a keyword virtual as :

Lets see how can we resolve this issue :
                    #include < iostream> 
                    using namespace std; 
                          
                    class A { 
                    public: 
                        int a; 
                        A() // constructor 
                        { 
                            a = 10; 
                        } 
                    }; 
                      
                    class B : public virtual A { 
                    }; 
                      
                    class C : public virtual A { 
                    }; 
                      
                    class D : public B, public C { 
                    }; 
                      
                    int main() 
                    { 
                        D object; // object creation of class d 
                        cout << "a = " << object.a << endl; 
                      
                        return 0; 
                    } 

                    Output :
                    a = 10
                
Explaination :

virtual can be written before or after the public. Now only one copy of data/function member will be copied to class C and class B and class A becomes the virtual base class. Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use virtual base.

The class A has just one data member a which is public. This class is virtually inherited in class B and class C. Now class B and class C becomes virtual base class and no duplication of data member a is done.

Pure Virtual Functions in C++ :

Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0. Here is the syntax for a pure virtual function,

                    virtual void f() = 0;
                

A class with at least one pure virtual function or abstract function is called abstract class. We can’t create an object of abstract class. Member functions of abstract class will be invoked by derived class object.

Lets take an Example :
                #include< iostream.h>
                #include< conio.h>
        
               class BaseClass       //Abstract class
               {
        
                      public:
                       virtual void Display1()=0;     //Pure virtual function or abstract function
                       virtual void Display2()=0;     //Pure virtual function or abstract function
        
                       void Display3()
                       {
                              cout<<"\n\tThis is Display3() method of Base Class";
                       }
        
               };
        
               class DerivedClass : public BaseClass
               {
        
                      public:
                       void Display1()
                       {
                              cout<<"\n\tThis is Display1() method of Derived Class";
                       }
        
                       void Display2()
                       {
                              cout<<"\n\tThis is Display2() method of Derived Class";
                       }
        
               };
        
               void main()
               {
        
                      DerivedClass D;
        
                      D.Display1();            // This will invoke Display1() method of Derived Class
                      D.Display2();            // This will invoke Display2() method of Derived Class
                      D.Display3();            // This will invoke Display3() method of Base Class
        
               }
        
            Output :
         
                       This is Display1() method of Derived Class
                       This is Display2() method of Derived Class
                       This is Display3() method of Base Class
         
                

Why we need a abstract class?:

Let’s understand this with the help of a real life example. Lets say we have a class Animal, animal sleeps, animal make sound, etc. For now I am considering only these two behaviours and creating a class Animal with two functions sound() and sleeping().

Now, we know that animal sounds are different cat says “meow”, dog says “woof”. So what implementation do I give in Animal class for the function sound(), the only and correct way of doing this would be making this function pure abstract so that I need not give implementation in Animal class but all the classes that inherits Animal class must give implementation to this function. This way I am ensuring that all the Animals have sound but they have their unique sound.

Lets take an example :
                #include
                using namespace std;
                class Animal{
                public:
                   //Pure Virtual Function
                   virtual void sound() = 0;
                
                   //Normal member Function
                   void sleeping() {
                      cout<<"Sleeping";
                   }
                };
                class Dog: public Animal{
                public:
                   void sound() {
                      cout<<"Woof"<< endl;
                   }
                };
                int main(){
                   Dog obj;
                   obj.sound();
                   obj.sleeping();
                   return 0;
                }
                

Important Points :

1) As we have seen that any class that has a pure virtual function is an abstract class.

2) We cannot create the instance of abstract class. For example: If I have written this line Animal obj; in the above program, it would have caused compilation error.

3) We can create pointer and reference of base abstract class points to the instance of child class. For example, this is valid:

                    Animal *obj = new Dog();
                    obj->sound();
                

4) Abstract class can have constructors.

5) If the derived class does not implement the pure virtual function of parent class then the derived class becomes abstract.

Keep in mind exam will 100 % ask objective questions on these topics .

Abstraction :

Abstraction is a process of hiding the implementation from the user, only the functionality is exposed here. So you are aware only of what the application does, not how it does it.

Real life Example :

When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.

Lets Start Some coding Exercises :

 
Note I am not attaching answers here this is your assignment so complete your assignment and mail us on help@ccatcracker.in .
 
1. Write a program in C++ to check whether a number is positive, negative or zero ?
 
                        Input : 
                        Enter a number : -4

                        Output :
                        This is a negative number 
                    
 
2. Write a language program in C++ which accepts the user’s first and last name and print them in reverse order with a space between them.
 
                       
                        Input First Name: ccat 
                        Input Last Name: cracker 
                        Name in reverse is: cracker ccat  
                    
 
3. Write C++ to check leap year . Create function of leap year and call it from main function ?
                        Input : 
                        Enter a year : 2016 

                        Output :

                        Not a leap year 
                    
 
4. Write a C++ program to compute the sum of the specified number of Prime numbers.
 
                            Enter a number  = 7,
                            Output  = 2 + 3 + 5 + 7 + 11 + 13 + 17 = 58.
                    
 
5. Write a C++ program to sum of all positive integers in a sentence.
 
                            Sample string: There are 25 chairs, 20 desks and 1 blackboard .
                            Output: 46