Pages

Wednesday, June 29, 2011

Types Of Inheritance

Inheritance Types

There are many different types of inheritances each with its own features and benefits. The following are the types of inheritances available in C++.
  •  Single Inheritance
Single Inheritance (Base Class - A, Child Class B)

When a child class is declared using the properties of a single base class, it is known as Single Inheritance. In this type of inheritance, the child class can access all the public and protected members of the parent as if they are its own.
Syntax
class child : access_specifier baseclass

Example
class student : public person

  •  Multiple Inheritance
Multiple Inheritance : Base Classes A & B
Child Class - C
When a child class is declared using the properties of more than one base class, it is termed as Multiple inheritance. In this case, the child class benefits more than it does in Single Inheritance since now it can access the members of more the one class. A class can inherit from as many classes as required. Similar to Single Inheritance, the child class can access only the  public and protected members of its parents.


Syntax
class child : access_specifier baseclass1, access_specifier baseclass2....
Example
class bike : public vehicle, public automobile

  • Multilevel Inheritance
B is both a parent and
a child
If a child class also acts as a parent class for another class, it is called Multilevel inheritance. In this type of Inheritance the intermediate class is both a child and a parent. 
In this type of inheritance, there are number of level and it has used in that cases where we want to use all properties in number of levels according to the requirement. For example, class A inherited in class b and class b has inherited in class c for class b so on. Where class A is base class c. In another way we can say b is derived class a base class for c and a indirect base class for c is indirect base class for c and c indirect derived class for class A.



  • Hierarchical Inheritance:
Class A has multiple child classes
This type of inheritance helps us to create a baseless for number of classes and those numbers of classes can have further their branches of number of class.

  • Hybrid Inheritance:
In this type of inheritance, we can have combinations of different types of inheritances. For example if there are many classes in a program some of them single inheritance while others can have multiple inheritance.

Monday, June 27, 2011

Inheritance and Access Specifiers

In this section, we’ll learn about the role of access specifiers in the inheritance process, as well as cover the different types of inheritance possible in C++.
To this point, you’ve seen the private and public access specifiers, which determine who can access the members of a class. As a quick refresher, public members can be accessed by anybody. Private members can only be accessed by member functions of the same class. Note that this means derived classes can not access private members!

class Base
{
private:
    int m_nPrivate; // can only be accessed by Base member functions (not derived classes)
public:
    int m_nPublic; // can be accessed by anybody
};
When dealing with inherited classes, things get a bit more complex.
First, there is a third access specifier that we have yet to talk about because it’s only useful in an inheritance context. The protected access specifier restricts access to member functions of the same class, or those of derived classes.

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};

class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:

        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};

int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}
Second, when a derived class inherits from a base class, the access specifiers may change depending on the method of inheritance. There are three different ways for classes to inherit from other classes: public, private, and protected.
To do so, simply specify which type of access you want when choosing the class to inherit from:

// Inherit from Base publicly
class Pub: public Base
{
};

// Inherit from Base privately
class Pri: private Base
{
};

// Inherit from Base protectedly
class Pro: protected Base
{
};

class Def: Base // Defaults to private inheritance
{
};
If you do not choose an inheritance type, C++ defaults to private inheritance (just like members default to private access if you do not specify otherwise).
That gives us 9 combinations: 3 member access specifiers (public, private, and protected), and 3 inheritance types (public, private, and protected).
The rest of this section will be devoted to explaining the difference between these.
Before we get started, the following should be kept in mind as we step through the examples. There are three ways that members can be accessed:
  • A class can always access it’s own members regardless of access specifier.
  • The public accesses the members of a class based on the access specifiers of that class.
  • A derived class accesses inherited members based on the access specifiers of its immediate parent. A derived class can always access it’s own members regardless of access specifier.
This may be a little confusing at first, but hopefully will become clearer as we step through the examples.
Public inheritance
Public inheritance is by far the most commonly used type of inheritance. In fact, very rarely will you use the other types of inheritance, so your primary focus should be on understanding this section. Fortunately, public inheritance is also the easiest to understand. When you inherit a base class publicly, all members keep their original access specifications. Private members stay private, protected members stay protected, and public members stay public.
class Base
{
public:
    int m_nPublic;
private:
    int m_nPrivate;
protected:
    int m_nProtected;
};

class Pub: public Base
{
    // Public inheritance means:
    // m_nPublic stays public
    // m_nPrivate stays private
    // m_nProtected stays protected

    Pub()
    {
        // The derived class always uses the immediate parent's class access specifications
        // Thus, Pub uses Base's access specifiers
        m_nPublic = 1; // okay: anybody can access public members
        m_nPrivate = 2; // not okay: derived classes can't access private members in the base class!
        m_nProtected = 3; // okay: derived classes can access protected members
    }
};

int main()
{
    // Outside access uses the access specifiers of the class being accessed.
    // In this case, the access specifiers of cPub.  Because Pub has inherited publicly from Base,
    // no access specifiers have been changed.
    Pub cPub;
    cPub.m_nPublic = 1; // okay: anybody can access public members
    cPub.m_nPrivate = 2; // not okay: can not access private members from outside class
    cPub.m_nProtected = 3; // not okay: can not access protected members from outside class
}


Points to remember :
  1. Derived classes can not directly access private members of the base class.
  2. The protected access specifier allows derived classes to directly access members of the base class while not exposing those members to the public.
  3. The derived class uses access specifiers from the base class.
  4. The outside uses access specifiers from the derived class.
To summarize in table form:
Public inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Public Yes Yes
Private Private No No
Protected Protected Yes No
Private inheritance
With private inheritance, all members from the base class are inherited as private. This means private members stay private, and protected and public members become private.
Note that this does not affect that way that the derived class accesses members inherited from its parent! It only affects the code trying to access those members through the derived class.
class Base
{
public:
    int m_nPublic;
private:
    int m_nPrivate;
protected:
    int m_nProtected;
};

class Pri: private Base
{
    // Private inheritance means:
    // m_nPublic becomes private
    // m_nPrivate stays private
    // m_nProtected becomes private

    Pri()
    {
        // The derived class always uses the immediate parent's class access specifications
        // Thus, Pub uses Base's access specifiers
        m_nPublic = 1; // okay: anybody can access public members
        m_nPrivate = 2; // not okay: derived classes can't access private members in the base class!
        m_nProtected = 3; // okay: derived classes can access protected members
    }
};

int main()
{
    // Outside access uses the access specifiers of the class being accessed.
    // Note that because Pri has inherited privately from Base,
    // all members of Base have become private when access through Pri.
    Pri cPri;
    cPri.m_nPublic = 1; // not okay: m_nPublic is now a private member when accessed through Pri
    cPri.m_nPrivate = 2; // not okay: can not access private members from outside class
    cPri.m_nProtected = 3; // not okay: m_nProtected is now a private member when accessed through Pri

    // However, we can still access Base members as normal through Base:
    Base cBase;
    cBase.m_nPublic = 1; // okay, m_nPublic is public
    cBase.m_nPrivate = 2; // not okay, m_nPrivate is private
    cBase.m_nProtected = 3; // not okay, m_nProtected is protected
}
To summarize in table form:
Private inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Private Yes No
Private Private No No
Protected Private Yes No
Protected inheritance
Protected inheritance is the last method of inheritance. It is almost never used, except in very particular cases. With protected inheritance, the public and protected members become protected, and private members stay private.
To summarize in table form:
Protected inheritance
Base access specifier Derived access specifier Derived class access? Public access?
Public Protected Yes No
Private Private No No
Protected Protected Yes No
Protected inheritance is similar to private inheritance. However, classes derived from the derived class still have access to the public and protected members directly. The public (stuff outside the class) does not.
Summary
The way that the access specifiers, inheritance types, and derived classes interact causes a lot of confusion. To try and clarify things as much as possible:
First, the base class sets it’s access specifiers. The base class can always access it’s own members. The access specifiers only affect whether outsiders and derived classes can access those members.
Second, derived classes have access to base class members based on the access specifiers of the immediate parent. The way a derived class accesses inherited members is not affected by the inheritance method used!
Finally, derived classes can change the access type of inherited members based on the inheritance method used. This does not affect the derived classes own members, which have their own access specifiers. It only affects whether outsiders and classes derived from the derived class can access those inherited members.
A final example:
class Base
{
public:
    int m_nPublic;
private:
    int m_nPrivate;
protected:
    int m_nProtected;
};
Base can access it’s own members without restriction. The public can only access m_nPublic. Derived classes can access m_nPublic and m_nProtected.
class D2: private Base
{
public:
    int m_nPublic2;
private:
    int m_nPrivate2;
protected:
    int m_nProtected2;
}
D2 can access it’s own members without restriction. D2 can access Base’s members based on Base’s access specifiers. Thus, it can access m_nPublic and m_nProtected, but not m_nPrivate. Because D2 inherited Base privately, m_nPublic, m_nPrivate, and m_nProtected are now private when accessed through D2. This means the public can not access any of these variables when using a D2 object, nor can any classes derived from D2.
class D3: public D2
{
public:
    int m_nPublic3;
private:
    int m_nPrivate3;
protected:
    int m_nProtected3;
};
D3 can access it’s own members without restriction. D3 can access D2′s members based on D2′s access specifiers. Thus, D3 has access to m_nPublic2 and m_nProtected2, but not m_nPrivate2. D3 access to Base members is controlled by the access specifier of it’s immediate parent. This means D3 does not have access to any of Base’s members because they all became private when D2 inherited them.

Thursday, June 23, 2011

Inheritance

What is Inheritance?

In real life a child inherits or gets different type of properties from his parent. These properties can be either biological (height, skin color, color of eyes etc) or monetory (Land, House, Money etc). Since these properties were not exactly earned by the child ,rather he got them from his parent all such properties will be called inherited properties and process will be known as Inheritance.
Similarly in OOPS, Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class.
For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc.


This concept of Inheritance leads to the concept of polymorphism.

Features or Advantages of Inheritance:
  • Reusability: 
Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed.
  • Saves Time and Effort:

 The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed.

  • Increases Program Structure which results in greater reliability.

     
  • Polymorphism 

Syntax
class derived_classname: access specifier baseclassname
For example, if the base class is example and the derived class is sample it is specified as:




class sample: public example


The above makes sample have access to both public and protected variables of base class example. Reminder about public, private and protected access specifiers:
  • If a member or variables defined in a class is private, then they are accessible by members of the same class only and cannot be accessed from outside the class. .
  • Public members and variables are accessible from outside the class. .
  • Protected access specifier is a stage between private and public. If a member functions or variables defined in a class are protected, then they cannot be accessed from outside the class but can be accessed from the derived class.

Inheritance Example:


class example
            {
public:
example(void) { x=0; }
void f(int n1)
{
x= n1*5;
}

void output(void) { cout<

private:
int x;
};


class sample: public example{
public:
sample(void) { s1=0; }

void f1(int n1)
{
s1=n1*10;
}


void output(void)
{
example::output();
cout << s1;
}


private:
int s1;
};


int main(void)
{
sample s;
s.f(10);
s.output();
s.f1(20);
s.output();
}



The output of the above program is

50
200

In the above example, the derived class is sample and the base class is example The derived class defined above has access to all public and private variables. Derived classes cannot have access to base class constructors and destructors. The derived class would be able to add new member functions, or variables, or new constructors or new destructors. In the above example, the derived class sample has new member function f1( ) added in it. The line:



sample s;

creates a derived class object named as s. When this is created, space is allocated for the data members inherited from the base class exforsys and space is additionally allocated for the data members defined in the derived class sample.


The base class constructor example is used to initialize the base class data members and the derived class constructor sample is used to initialize the data members defined in derived class.

Constructor - Source Code

Problem :
Write a Circle class that has Radius a data member, also using a constructor that sets the radius value by set and get functions. Then it prints the Area, Circumference, and the Diameter of that Circle.”

Solution

class Circle // creating class called circle
{
public:

// constructor initializes radius with double supplied as argument
Circle( double rad )
{
setradius( rad ); // call set function to initialize radius
} // end Circle constructor

void setradius( double rad )
{
radius = rad;

if ( radius < 0 )
{
radius = 0;
}
}

double getradius()
{

return radius;

}

double diameter()
{

double r;

r = getradius();

return 2*r;

}

double circumference()
{

double c;

c = getradius();

return 2*3.14*c;

}

double area()
{

double a;

a = getradius();

return 3.14*a*a;

}

void displayMessage()
{
cout << "The Radius is: " << getradius() << "\nThe Diameter is: " << diameter() << "\nThe Circumference is: " << circumference() << "\nThe Area is: " << area() << endl;

}

private:

double radius;

};


// function main allow program to execution
int main()
{


Circle C(1.5); // Creating an object from the class and send the constructor 1.5 as the Radius value.



C.displayMessage();


return 0;

} // end function main

Copy Constructor

Copy Constructor are also the special type of constructors in C++ and they have got a specfic syntax.

The syntax is,
const classname& classname(const classname& other);

There are many ways copy constructors gets called.
1. When the object gets copied explicitly or implicitly
2. When the object gets initialized.

Source Code


class MyClass
{
private:
int m;
int a;
int b;
public:
MyClass() : a(10), b(20), m(30)
{
};
// Syntax for copy constructor
MyClass(const MyClass &other)
{
this->a = other.a;
this->b = other.b;
this->m = other.m;
}
// Syntax for assignment operator
const MyClass& operator = (const MyClass &other)
{
this->a = other.a;
this->b = other.b;
this->m = other.m;
return *this;
}
};
void main()
{
MyClass a; // calls default constructor
MyClass c; // calls default constructor
MyClass b = a; // calls copy constructor
c = b; // calls assignment operator
}

Constructor - Source Code

class MyString
{
private:
char *m_pString;
public:
MyString()
{
std::cout << "Calling Default Constructor\n";
m_pString = NULL;
}
~MyString()
{
if( this->m_pString != NULL)
{
std::cout << "Calling Destructor\n";
delete this->m_pString;
this->m_pString = NULL;
}
}
MyString(const char *p)
{
std::cout << "Calling Parameterized Constructor\n";
int len = strlen(p);
m_pString = new char [len + 1];
strcpy(m_pString, p);
}
MyString(const MyString &other)
{
std::cout << "Calling Copy Constructor\n";
m_pString = other.m_pString;
//int len = strlen(other.m_pString);
//m_pString = new char [len + 1];
//strcpy(m_pString, other.m_pString);
}
const MyString& operator = (const MyString &other)
{
std::cout << "Calling assignment operator\n";
int len = strlen(other.m_pString);
m_pString = new char [len + 1];
strcpy(m_pString, other.m_pString);
return *this;
}
operator const char*()
{
return this->m_pString;
}
};