Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts

Sunday, January 13, 2013

Virtual Inheritance

Virtual inheritance:
                        Inheritance can be private (where even the public fields of the base class are treated as private), public (where the base class determines visibility), or virtual. With virtual inheritance there is only one copy of each object even if (because of multiple inheritance) the object appears more than once in the hierarchy. In the following example, derived1a and derived1b each contain a base object, butderived2 contains just one field.

#include <iostream>
using namespace std;

class base{
    public:
        int i;
};

class derived1a: virtual public base {
    public:
        int j;
};

class derived1b: virtual public base {
    public:
        int k;
};

class derived2: public derived1a, public derived1b{
    public:
        int product(){
            return i*j*k;
        }
};

int main()
{
    derived2 obj;
    obj.i = 10;
    obj.j = 3;
    obj.k = 5;
   
    cout << "\n product is " << obj.product() << '\n';
    return 0;
}

OUTPUT:

Tuesday, August 14, 2012

virtual inheritance and runtime polymorphism

// Using dot net and C#
using System;

public class a
{
    public void Hockey()
    {
        Console.WriteLine("A play hockey");
    }

    public virtual void education()
    {
        Console.WriteLine("MBBS");
    }

}
public class b:a
{
    public void cricket()
    {
        Console.WriteLine("B play cricket");
    }
    public override void education()
    {
        Console.WriteLine("MCA");
    }
}

class demo
{
    public static void Main()
    {
        a a1=new b();            //run time polymorphism
        a1.education();
        Console.ReadLine();
    }
}


OUTPUT:

To see in c++ CLICK HERE

Monday, July 2, 2012

Relation between class_Size and inheritance

#include <iostream>
using namespace std;

class Base
{
    int first_int;           //size of int is 4 byte
    int second_int;       //so size of Base class is 8 byte
};

class derived:public Base
{
    int derived_member;
    int another_derived_member;
    int new_member;
};

class home
{
    Base base_1;
    Base base_2;
};

int main()
{
    cout << sizeof(derived) << endl;     //the size of derived class is (8+12=20) byte
    cout << sizeof(Base)    << endl;
    cout << sizeof(home)   << endl;      //the size of home class is (8+8)=16 byte
}


OUTPUT:
20
8
16