class and object in c++ by pawan thakur

38
7.1. INTRODUCTION Classes extend the built-in capabilities of C++ able you in representing and solving complex, real-world problems. A class is an organization of data and functions which operate on them. Data structures are called data members and the functions are called member functions, the combination of data members and member functions constitute a data object or simply an object. Class is a group of data member and member functions. Another word class is a collection of objects of similar type. To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class declaration ends with a semi-colon. The name of a class follows the rules we have applied for variable and function names. To declare a class you would type the following: syntax: class class_name { access_specifier_1: shift hight one tab ------------------- ---------------------data member and member functions LEARNING OBJECTIVES At the end of this chapter you will be able to understand : Concepts of Classes Objects Construction and Destructor Overloading Inheritence L

Upload: pawan-thakur

Post on 19-Aug-2014

111 views

Category:

Education


19 download

DESCRIPTION

Classes extend the built-in capabilities of C++ able you in representing and solving complex, real-world problems. A class is an organization of data and functions which operate on them. Data structures are called data members and the functions are called member functions, the combination of data members and member functions constitute a data object or simply an object. Class is a group of data member and member functions. Another word class is a collection of objects of similar type. To create a class, use the class keyword followed by a name for the object. Like any other declared variable, the class declaration ends with a semi-colon. The name of a class follows the rules we have applied for variable and function names.

TRANSCRIPT

Page 1: Class and object in C++ By Pawan Thakur

7.1. INTRODUCTION

Classes extend the built-in capabilities of C++ able you in representing and solving complex,real-world problems. A class is an organization of data and functions which operate onthem. Data structures are called data members and the functions are called memberfunctions, the combination of data members and member functions constitute a dataobject or simply an object.

Class is a group of data member and member functions. Another wordclass is a collection of objects of similar type.

To create a class, use the class keyword followed by a name for the object. Like anyother declared variable, the class declaration ends with a semi-colon. The name of a classfollows the rules we have applied for variable and function names. To declare a class youwould type the following:

syntax:

class class_name{access_specifier_1: shift hight one tab----------------------------------------data member and member functions

LEARNING OBJECTIVES

At the end of this chapter you will be able to understand :

� Concepts of Classes

� Objects

� Construction and Destructor

� Overloading

� Inheritence

L

Page 2: Class and object in C++ By Pawan Thakur

7-2 CLASSES AND OBJECTS

………………….access_specifier_2:----------------------------------------data member and member functions………………….} ;

Where class_name is a valid identifier for the class. The body of the declaration cancontain members, that can be either data or function declarations, or optionally accessspecifiers. All is very similar to the declaration on data structures, except that we can nowinclude also functions and members, but also this new thing called access specifier. Anaccess specifier is one of the following three keywords: private, public or protected.These specifiers modify the access rights that the members following them acquire:

(a) Private members-: Private members of a class are accessible only from within othermembers of the same class or from their friends.

(b) Protected members-: Protected members are accessible from members of theirsame class and from their friends, but also from members of their derived classes.

(c) Public members-: Public members are accessible from anywhere where the object isvisible.

By default, all members of a class declared with the class keyword have private accessfor all its members. Therefore, any member that is declared before one other classspecifier automatically has private access. The program 7.1 demonstrates the concept ofclass.

Example 7.1. A class Example

class demo{int x,y,z;public:void getxy(){cout<<"Enter the value of X";cin>>x;cout<<"Enter the value of Y";cin>>y;}void getsum(){z=x+y;cout<<"The result "<<z;}};

Declares a class called demo. This class contains five members: three data members oftype int x, y and z with private access because private is the default access level. Twomember functions with public access: getxy() and getsum() and their definition.

Page 3: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-3

7.1.1. Class ObjectsAn object is an individual instance of a class object is a variable of type class. You definean object of your new type just as you define an integer variable:

L Object is an instance of class which is use to access the members of class.

Syntax-:

Class_name object_name;Example-:int a; // define integerdemo ob; // define a object ob of class demo

This code defines a variable called a type is an integer. It also defines an object ob whoseclass is demo. The program 7.2 demonstrates the concept of object.

Object name can be any identifies name.

Example 7.2. A class Example with Object.

class demo{int x,y,z;public:void getxy(){cout<<"Enter the value of X";cin>>x;cout<<"Enter the value of Y";cin>>y;}void getsum(){z=x+y;cout<<"The result "<<z;}};void main(){clrscr();demo ob;}

7.1.2. Accessing Class MembersOnce you define an actual object for class for example, ob for demo class. We can usethe dot operator (.) to access the members of that object. The program 7.3 display theexample of access the member of class, in this example we are calling getxy() and getsum()functions of demo class.

Page 4: Class and object in C++ By Pawan Thakur

7-4 CLASSES AND OBJECTS

Program 7.3. Accessing class Members.

class demo{int x, y, z;public:void getxy(){cout<<"Enter the value of X";cin>>x;cout<<"Enter the value of Y";cin>>y;}void getsum(){z=x+y;cout<<"The result "<<z;}};void main(){clrscr();demo ob;ob.getxy();ob.getsum(); // include commentsgetch();}

Output-:

7.1.3.Defined Member FunctionWe can define the member function of a in to way: Inside the class and outside the class

(a) Define the Member Function Inside the class. One method of defining a memberfunction is to replace the function declaration by the actual function definition inside theclass. The program 7.4 shown in the below, illustrates how to define a member functioninside the class definition.

Page 5: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-5

Program 7.4. Defining the Members function Inside the Class.

#include<iostream.h>#include<conio.h>class Inside_demo{int x,y;public:void getxy() // member function inside the class{cout<<"Enter the value of X";cin>>x;cout<<"Enter the value of Y " ;cin>>y;}void greater() //{if(x>y)cout<<"X is Greater";elsecout<<"Y is Greater";}};void main(){clrscr();Inside_demo ob1;ob1.getxy();ob1.greater();getch();}

Output-:

(b) Define the Member Function Outside the class. Another method of defining amember function is to replace the function declaration by the actual function definitionoutside the class. The program 7.5 shown in the below only members of rect that we

Page 6: Class and object in C++ By Pawan Thakur

7-6 CLASSES AND OBJECTS

cannot access from the body of our program outside the class are x and y, since theyhave private access and they can only be referred from within other members of thatsame class. Here is the complete example of class CRectangle:

Program 7.5. Defining the Members function Inside the Class.

#include <iostream.h>#include<conio.h>class CRectangle{int x, y;public:void set_values (int, int);int area(){return (x*y);}};void CRectangle::set_values (int a, int b){ // member function outside the classx = a;y = b;}void main(){clrscr();CRectangle rect;rect.set_values(3,4);cout << "area: " << rect.area();getch();}

Output-:

Scope Resolution Operator : The most important new thing in this code is the operatorof scope (::, two colons) included in the definition of set_values(). It is used to define amember of a class from outside the class definition itself.

You may notice that the definition of the member function area() has been includeddirectly within the definition of the CRectangle class given its extreme simplicity, whereasset_values() has only its prototype declared within the class, but its definition is outside it.In this outside declaration, we must use the operator of scope (::) to specify that we aredefining a function that is a member of the class CRectangle and not a regular globalfunction.

Page 7: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-7

The scope resolution operator (::) specifies the class to which the member being declaredbelongs, granting exactly the same scope properties as if this function definition wasdirectly included within the class definition. For example, in the function set_values() ofthe previous code, we have been able to use the variables x and y, which are privatemembers of class CRectangle, which means they are only accessible from other membersof their class.

7.2. CONSTRUCTOR

A constructor is a 'special' member function whose task is to initialize the object of itsclass. It is special because its name is the same as the class name. The constructor isinvoked whenever an object of its associated class is created. It is called constructorbecause it constructs the values of data members of the class.

A constructor is a ‘special’ member function which initializes the object ofits class.

A constructor is declared and defined as follows:

syntax:

class integer{int m,n;public:integer (void); // constructor declared--------};integer :: integer (void) // constructor . defined{m=0;n=0;}

When a class contains a constructor like the one defined above, it is guaranteed that anobject created by the class will be initialized automatically. For example,

integer obj1 ; // Object obj1 created

Not only creates the objects, obj1 is of type integer and also initializes its data membersm ands n to zero. There is no need to write any statement to invoke the constructorfunction as we do with the normal member functions.

7.2.1. Properties of ConstructorThe constructor functions have some special characteristics.

1. It should be declared in the public section of the class.

2. They are invoked automatically when the objects are created.

L

Page 8: Class and object in C++ By Pawan Thakur

7-8 CLASSES AND OBJECTS

3. They do not have return types, not even void. Therefore, they cannot returnvalues.

4. They cannot be inherited, though a derived class can call the base class constructor.

5. Like other C++ functions, they can have default arguments.

6. Constructor alone have the same name as class.

7.2.2. Default ConstructorIf you do not declare any constructors in a class definition, the compiler assumes theclass to have a default constructor with no arguments.

L A constructor that accepts no parameters is called ‘Default Constructor’.

The program 7.6 displays the example of default constructor.

Program 7.6. Default constructor

#include<iostream.h>#include<conio.h>class CExample{public:CExample(){cout<<"Default Constuctor Example"}};void main(){CExample ex;getch();}

Output-:

The compiler assumes that CExample has a default constructor, so you can declareobjects of this class by simply declaring them without any arguments:

Page 9: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-9

7.2.3.Parameterized ConstructorsWe know that constructor initialize the data members of all the objects to zero. However,in practice it may be necessary to initialize the various data elements of different objectswith different values when they are created C++ permits us to achieve this objective bypassing arguments to the constructor function when the subjects are created.

The constructors that can take arguments are called parameterizedconstructors.

The program 7.7 displays the example of parameterized constructors.

Program 7.7. Parameterized constructor

#include<iostream.h>#include<conio.h>class CExample{public:int a,b,c;CExample (int n, int m) // parameterized constructor{a=n;b=m;};void multiply(){c=a*b;cout<<"The Mulplication "<<c;}};void main(){CExample ex(2,3);ex. multiply();getch();}

Output-:

L

Page 10: Class and object in C++ By Pawan Thakur

7-10 CLASSES AND OBJECTS

Here we have declared a constructor that takes two parameters of type int. Therefore thefollowing object declaration would be correct:

CExample ex (2,3);

But,

CExample ex;

Would not be correct, since we have declared the class to have an explicit constructor,thus replacing the default constructor.

But the compiler not only creates a default constructor for you if you do not specify yourown. It provides three special member functions in total that are implicitly declared if youdo not declare your own. These are the copy constructor, the copy assignment operator,and the default destructor.

7.2.4.Copy ConstructorA copy constructor takes a reference to an object of the same class as itself as anargument.

A copy constructor is used to declare and initialize an object from anotherobject.

For example, the statement integer obj1(obj2); Would define the object obj2 and at thesame time initialize is to value of obj1. Another form of this statement is.

Integer obj2=obj1;

The process of initializing through a copy constructor is known as copy initialization.Remember, the statement

Obj2= obj1;

Will not invoke the copy constructor. However if obj1 and obj2 are objects, this statementis legal and simply assigns the values of obj1 to obj2, member by member. This is task ofthe overloaded assignment operator (=).The program 7.8 displays the example of copyconstructors.

Program 7.8. Copy constructor

# include<iostream.h>#include<conio.h>class code{int id;public:code() // constructor{}code (int a) // constructor again{id=a;

L

Page 11: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-11}code(code &x) // copy constructor{id=x.id;}void display(void){cout<<id;}};int main(){code A(100);code(A);code C=A;code D;D=A;cout << "\n id of A:";C.display();cout<< "\n id of B:";C.display();cout<< "\n id of C:";C.display();cout<< "\n id of D:";D. display();return 0;}

Output:

Page 12: Class and object in C++ By Pawan Thakur

7-12 CLASSES AND OBJECTS

7.3. DESTRUCTOR

Like a constructor, the destructor is a member function whose name is the same as theclass name but it is preceded by a 'tilde' ~ sign.

A destructor is a member function used to destroy the objects that havebeen created by a constructor.

For example, the destructor for the class integer can be defined as shown below:

Syntax:

~ integer (){--------------- body of destructor}

A destructor never takes any argument nor does return any value. It will be invokedimplicitly by the complier upon exit from the program (or block or function as the casemay be) to clean up storage, that is, no longer accessible. It is a good practice to declaredestructors in a program. Since it releases memory for future use. Whenever ‘new’ isused to allocate memory in the constructors, we should use ‘delete’ to free that memory.The program 7.9 displays the example of destructor.

Program 7.9. Example of destructor

# include<iostream.h>#include<conio.h>int count = 0;class alpha{public:alpha(){count ++ ;cout << "\n No. of objected created " << count;}~ alpha(){cout<< "No. of object destroyed" << count;count --;}};int main(){cout << "\n Enter main";alpha A1,A2,A3,A4;{cout<< "\n Enter Block 1\n";

L

Page 13: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-13alpha A5 ;}cout << "\n enter block 2\n";alpha A6;getch();}

Output:

7.4. OVERLOADING

Overloading is one of the many exciting features of C++ language. It is an importanttechnique that has enhanced the power of extensibility of C++. This feature of C++ helpto write general function to perform more than one task with signal function name.

7.4.1. Function OverloadingC++ permits the use of more than one functions with the same name. However suchfunctions essentially have different argument list. The difference can be in terms ofnumber or type of arguments or both.

This process of using two or more functions with the same name butdiffering in the signature is called function overloading.

But overloading of functions with different return types are not allowed. In overloadedfunctions, the function call determines which function definition will be executed. Thebiggest advantage of overloading is that it helps us to perform same operations on differentdata types without having the need to use separate names for each version. The program7.10 displays the example of function overloading..

L

Page 14: Class and object in C++ By Pawan Thakur

7-14 CLASSES AND OBJECTS

Program 7.10. Example of Function overloading

#include<iostream.h>#include<conio.h>int abslt(int);long abslt(long);float abslt(float);double abslt(double);int main(){int intgr=-5;long lng=34225;float flt=-5.56;double dbl=-45.6768;cout<<" absoulte value of "<<intgr<<" = "<<abslt(intgr)<<endl;cout<<" absoulte value of "<<lng<<" = "<<abslt(lng)<<endl;cout<<" absoulte value of "<<flt<<" = "<<abslt(flt)<<endl;cout<<" absoulte value of "<<dbl<<" = "<<abslt(dbl)<<endl;}int abslt(int num){ if(num>=0) return num; else return(-num);}long abslt(long num){ if(num>=0) return num; else return(-num);}float abslt(float num){ if(num>=0) return num; else return(-num);}double abslt(double num){ if(num>=0) return num; else return(-num);}

Page 15: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-15

Output:

The above function finds the absolute value of any number int, long, float ,double. In C,the above is implemented as a set of different function abs()-for int, fabs()-for double,labs()-for long.

7.4.2.Operator OverloadingWe know that C++ tries to make the user defined data types behave in much the sameway as the built in types. For instance, C++ permits us to add two variables of user-defined types with the same syntax that is applied to the basic types. This means thatC++ has the ability to prove the operator with a special meaning for a data type.

The mechanism of giving such special meaning to an operator is knownas “Operator overloading”.

We can overload all the C++ operators except the following.

(a) Class member access operators (. , *)

(b) Scope resolution operator ( : : )

(c) Size operator (sizeof)

(d) Conditional operator (?: )

7.4.3. Rules for Operator OverloadingAlthough it looks simple to redefine the operators, there are certain restrictions andlimitations in overloading them. Some of them are listed below: -

(1) Only existing operator can be overloaded. New operator cannot be created.

(2) The overloaded operator must have at least one operands that is of user definedtype.

(3) We cannot change the basic meaning of an operator. That is to say, we cannotredefine the plus (+) operator to subtract one value from the other.

(4) There are some operators that can not overloaded like ., *, ::, ? :

L

Page 16: Class and object in C++ By Pawan Thakur

7-16 CLASSES AND OBJECTS

(5) We cannot use friend functions to overload certain operators. However, memberfunctions can be used to overload them. Operators like, = (assignment operator),()Function call operator ,[ ] (subscripting operator ) and - > (class member accessoperator).

The program 7.11 displays the example to overload greater than (>) sign to compare twostrings using friend function.

Program 7.11. Example of Operator overloading

#include <iostream.h>#include <conio.h>#include <string.h>class over{char nm[10];public :void getdata(){cout<<"Enter any string \n";cin>>nm ;}void putdata(){cout<<"Big string= "<<nm;}friend int operator>(over s1, over s2);};int operator>(over S1, over S2) // function to overload ‘7’ operator{if (strcmp(S1.nm,S2.nm)>0)return 1 ;elsereturn 0 ;}void main(){over S1, S2;S1.getdata();S2.getdata();if(S1>S2)cout<<"the first string is bigger:";elsecout<<"second string is bigger:";getch () ;}

Page 17: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-17

Output-:

7.4.4. Unary Operator OverloadingA unary operator is an operator that performs its operation on only one operand. ForExample, the increment operator is a unary operator. It operates on only one object. Usethe keyword operator, followed by the operator to overload. Unary operator functions donot take parameters, with the exception of the postfix increment and decrement, whichtake an integer as a flag. The program 7.12 displays the example to overload unary minusoperator.

Program 7.12. Example of unary operator overloading

#include<iostream.h>#include<conio.h>class unary_minus{private:int a;public:void input();void operator - (); //Declaration of operator function

// to overload unary minus operatorvoid show();};void unary_minus :: input(){cout<<"Enter the value of a:";cin>>a;}void unary_minus :: operator-() //Definition of operator{a=-a;}void unary_minus :: show (){cout<<"\na is: "<<a;}void main(){unary_minus obj;

Page 18: Class and object in C++ By Pawan Thakur

7-18 CLASSES AND OBJECTS

clrscr();obj.input();cout<<"\nBefore overloading\n";obj.show();-obj; //Calling operator functioncout<<"\nAfter overloading\n";obj.show();getch();}

Output-:

7.4.5. Binary Operator OverloadingAn operator is referred to as binary if it operates on two operands. For Example, theaddition operator (+) is a binary operator, where two objects are involved. Binary operatorsare created like unary operators, except that they do take a parameter. The parameter is aconstant reference to an object of the same type. The program 7.13 displays the exampleto add two compound numbers overload binary operator.

Program 7.13. Example of binary operator overloading

#include<iostream.h>#include<conio.h>class over{private:int x,y;public:void getdata();{cout<< "Enter two No. \n" ;cin>>x>>y;}void putdata(){

Page 19: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-19cout<<"\n<<x<<"\t"<<y;}friend operator +(overa1, overa2){over temp ;temp.x= a1.x+a1.y;temp.y = a2.y+a2.y;return temp ;}};void main(){over a1,a2,a3;clrscr();a1.getdata(); a2.getdata();a3=a1+a2; // overloadinggetch() ; }

7.5. DERIVED CLASS DECLARATION

Derived classes are supersets of their base classes. Typically, a base class will have morethan one derived class. Classes that are derived from others inherit all the accessiblemembers of the base class. That means if a base class includes a member A and wederive it to another class with another member called B, the derived class will containboth members A and B.

In order to derive a class from another, we use a colon (:) in the declaration of the derivedclass using the following format:

Syntax:

Class derived-class-name: accessibility-mode base-class-name{member data…………. //member function};

The colon indicates that the derived class name is derived from the base-class name. Theaccessibility mode is optional and, if present, may be either private or public. The defaultaccessibility mode is private. Accessibility mode specifies whether the features of thebase class are privately derived or publicly derived. The program 7.14 displays the exampleof derived class.

Program 7.14. Example of derived class

#inclue<iostream.h>#include<conio.h>class Base

Page 20: Class and object in C++ By Pawan Thakur

7-20 CLASSES AND OBJECTS

{int x;public:Base(){x=0;}void f(int n1){x= n1*5;}void output(){cout<<x<<endl;}};class Derived: public Base{int s1;public:Derived(){s1=0;}void f1(int n1){s1=n1*10;}void output(){Base::output();cout << s1<<endl;}};void main(){Derived s;s.f(10);s.output();s.f1(20);s.output(); getch();}

Page 21: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-21

Output:

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

Deived s;

Creates a derived class object named as s. When this is created, space is allocated for thedata members inherited from the base class Base and space is additionally allocated forthe data members defined in the derived class Deived. The base class constructor Base isused to initialize the base class data members and the derived class constructor Deived isused to initialize the data members defined in derived class.

7.6. INHERITANCE

Inheritance is the process by which new classes (called derived classes) are created fromexisting classes (called base classes). The derived classes have all the features of the baseclass and the programmer can choose to add new features specific to the newly createdderived class.

The mechanism of deriving a new class form the base class is calledinheritance.

For example, a programmer can create a base class named fruit and define derivedclasses 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 orfeatures specific to these newly created derived classes. Mango would have its owndefined features, orange would have its own defined features, banana would have itsown defined features, etc.

The derived class can inherit some or all the properties of the base class and can also passon the inherited properties to the class which will be inherited from it. It depends on theaccessibility level of the data and functions of the base class and the way the base class is

L

Page 22: Class and object in C++ By Pawan Thakur

7-22 CLASSES AND OBJECTS

inherited. The accessibility levels and the way of derivation can be- Private, Protectedand Public.

Fig. 7.1. Type of accessibility Modes.

From the above Fig. 7.1 it is clear that only the Protected and Public members areinherited and not the Private members. And inherited members will be available forfurther inheritance only if they are inherited in public way or protected way otherwisenot.

7.6.1. Features or Advantages of Inheritance(a) Reusability. Inheritance helps the code to be reused in many situations. The baseclass is defined and once it is compiled, it need not be reworked. Using the concept ofinheritance, the programmer can create as many derived classes from the base class asneeded while adding specific features to each derived class as needed.

(b) Saves Time and Effort. The above concept of reusability achieved by inheritancesaves the programmer time and effort. Since the main code written can be reused invarious situations as needed.

(c) Reliability. Increases Program Structure which results in greater reliability.

7.6.2. Types OF InheritanceThere are five forms of Inheritance:

1. Single Inheritance

2. Multiple Inheritance

3. Multi- Level Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

1. Single inheritance. The process of deriving only one new class from single base classis called single inheritance as shown in Fig. 7.2.

Page 23: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-23

Fig. 7.2. Single Inheritance.

Here A is the base class and B is the derived class. The program 7.15 displays theexample of single inheritance.

Program 7.15. Example Single Inheritance

#include<iostream.h>#include<conio.h>class person //Declare base class{private:char name[30];int age;char address[50];public:void get_data();void put_data();};class student : private person //Declare derived class{private:int rollno;float marks;public:void get_stinfo();void put_stinfo();};void person::get_data(){cout<<"Enter name:";cin>>name;cout<<"Enter age:";cin>>age;cout<<"Enter address:";cin>>address;}void person::put_data(){cout<<"Name: " <<name;cout<<"Age: " <<age;

Page 24: Class and object in C++ By Pawan Thakur

7-24 CLASSES AND OBJECTS

cout<<"Address: " <<address;}void student::get_stinfo(){get_data();cout<<"Enter roll number:";cin>>rollno;cout<<"Enter marks:";cin>>marks;}void student::put_stinfo(){put_data();cout<<"Roll Number:"<<rollno;cout<<"Marks:"<<marks;}void main(){student ob;clrscr();ob.get_stinfo();ob.put_stinfo();getch();}

Output :

Here ‘person’ is base class and ‘student’ is derived class that has been inherited fromperson privately. The private members of the ‘person’ class will not be inherited. Thepublic members of the ‘person’ class will become private members of the ‘student’ classsince the type of the derivation is private. Since the inherited members have becomeprivate they can not be accessed by the object of the ‘student’ class.

2. Multiple inheritance. The process of deriving only one new class from multiple baseclasses is called multiple inheritances as shown in Fig. 7.3.

Page 25: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-25

Fig. 7.3. Multiple Inheritance.

Here B1, B2 and B3 are the base classes and D is the derived class. The program 7.16displays the example of Multiple inheritance.

Program 7.16. Example Multiple Inheritance

#include<iostream.h>#include<conio.h>class A{protected:int x;};class B{protected:int y;};class C{protected:int z;};class D : private A, private B, private C{private:int sum;public:void get_data(){cout<<"Enter data:";cin>>x>>y>>z;}void add(){sum=x+y+z;cout<<"\nThe sum is:"<<sum;}};void main()

Page 26: Class and object in C++ By Pawan Thakur

7-26 CLASSES AND OBJECTS

{D ob;clrscr();ob.get_data();ob.add();getch();}

Here ‘B1’, ‘B2’ and ‘B3’ are base classes and ‘D’ is derived class that has been inheritedfrom all three classes privately. The members of the base classes have been declared asprotected. They will become private members of the ‘D’ class since the type of thederivation is private. Since the inherited members have become private they can not beaccessed by the object of the ‘D’ class.

3. Multi level inheritance. The process of deriving only one new class from the class thathas already been derived from some other class as shown in Fig. 7.4.

Fig. 7.4. Multi level inheritance.

Here C is derived from B which has already been derived from A. There can be anynumber of levels. The program 7.17 displays the example of multilevel inheritance.

Program 7.17. Example Multi level Inheritance

#include<iostream.h>#include<conio.h>class person{private:char name[30];int age;char address[50];public:

Page 27: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-27void get_pdata(){cout<<"Enter name:";cin>>name;cout<<"\nEnter age:";cin>>age;cout<<"\nEnter address:";cin>>address;}void put_pdata(){cout<<"\nName: "<<name;cout<<"\nAge: "<<age;cout<<"\nAddress: "<<address;}};class student : public person{private:int rollno;char course[10];public:void get_stdata(){cout<<"\nEnter roll number:";cin>>rollno;cout<<"\nEnter course:";cin>>course;}void put_stdata(){cout<<"\nRoll Number:"<<rollno;cout<<"\nCourse:"<<course;}};class performance : public student{private:float test1,test2,test3,per;public:void input(){cout<<"\nEnter marks of test 1:";cin>>test1;cout<<"\nEnter marks of test 2:";cin>>test2;cout<<"\nEnter marks of test 3:";cin>>test3;}void calc(){per=((test1+test2+test3)/30)*100;

Page 28: Class and object in C++ By Pawan Thakur

7-28 CLASSES AND OBJECTS

}void show(){cout<<"\nPercentage of the student is:"<<per;}};void main(){performance ob;clrscr();ob.get_pdata();ob.get_stdata();ob.input();ob.calc();ob.put_pdata();ob.put_stdata();ob.show();getch();}

Output :

Here ‘person’ is the base class from which ‘student’ has been derived publicly so thepublic members of the ‘person’ class will become public members of the ‘student’ class

Page 29: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-29

and can further be inherited. Then the ‘student’ class is inherited by the ‘performance’class publicly so the public members of ‘student’ class will become public members ofthe ‘performance’ class. These members will include those public members of the ‘student’class which are of its own and also those which it has inherited from ‘person’ class. So allthese members will be inherited by the ‘performance’ class. But the private members willnot be inherited.

4. Hierarchical inheritance. The process of deriving two or more classes from singlebase class. And in turn each of the derived classes can further be inherited in the sameway as shown in Fig. 7.5. Thus it forms hierarchy of classes or a tree of classes which isrooted at single class.

Fig. 7.5. Hierarchical Inheritance.

Here A is the base class from which we have inherited two classes B and C. From class Bwe have inherited D and E and from C we have inherited F and G. Thus the wholearrangement forms a hierarchy or tree that is rooted at class A. The program 7.18 displaysthe example of multilevel inheritance.

Program 7.18. Example Hierarchical Inheritance

#include<iostream.h>#include<conio.h>class person{private:char name[30];int age;char address[50];public:void get_pdata(){cout<<"Enter the name:";cin>>name;

Page 30: Class and object in C++ By Pawan Thakur

7-30 CLASSES AND OBJECTS

cout<<"\nEnter the address:";cin>>address;}void put_pdata(){cout<<"Name: "<<name;cout<<"\nAddress: "<<address;}};class student : private person{private:int rollno;float marks;public:void get_stdata(){get_pdata();cout<<"\nEnter roll number:";cin>>rollno;cout<<"\nEnter marks:";cin>>marks;}void put_stdata(){put_pdata();cout<<"\nRoll Number: "<<rollno;cout<<"\nMarks: "<<marks;}};class faculty : private person{private:char dept[20];float salary;public:void get_fdata(){get_pdata();cout<<"\nEnter department:";cin>>dept;cout<<"\nEnter salary:";cin>>salary;}void put_fdata(){put_pdata();cout<<"\nDepartment: "<<dept;cout<<"\nSalary: "<<salary;}};void main()

Page 31: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-31{student st;faculty fac;clrscr();cout<<"Enter the details of the student:\n";st.get_stdata();cout<<"\nEnter the details of the faculty member:\n";fac.get_fdata();cout<<"\nStudent info is:\n";st.put_stdata();cout<<"\nFaculty Member info is:\n";fac.put_fdata();getch();}

Output :

Page 32: Class and object in C++ By Pawan Thakur

7-32 CLASSES AND OBJECTS

Here ‘person’ is the base class from which ‘student’ and ‘faculty’ classes have beenderived privately so the public members of the ‘person’ class will become private membersof the ‘student’ class and ‘faculty’ class. But the private members will not be inherited.

5. Hybrid inheritance. When we combine two more types of inheritances, the resultantinheritance is called hybrid inheritance. Here we have combined two types of inheritances,multilevel inheritance and multiple inheritances. So result will be called hybrid inheritance.The program 7.19 displays the example of multilevel inheritance.

Fig. 7.6. Hybrid inheritance.

Program 7.19. Example Hierarchical Inheritance

#include<iostream.h>#include<conio.h>class student{private:char name[30];int rollno;char course[10];public:void get_stdata(){cout<<"Enter name:";cin>>name;cout<<"\nEnter roll number:";cin>>rollno;}void put_stdata(){cout<<"\nName:"<<name;cout<<"\nRoll Number:"<<rollno;}};class class_test : public student{protected:float ct_marks;public:

Page 33: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-33void get_ctmarks(){cout<<"\nEnter class test marks:";cin>>ct_marks;}void put_ctmarks(){cout<<"\nClass Test Marks: "<<ct_marks;}};class MST{protected:float mst_marks;public:void get_mstmarks(){cout<<"\nEnter MST marks:";cin>>mst_marks;}void put_mstmarks(){cout<<"\nMST Marks: "<<mst_marks;}};class performance : public class_test, public MST{private:float total_marks;public:void total(){total_marks=ct_marks+mst_marks;cout<<"\nTotal marks of the student are: "<<total_marks;}};void main(){performance ob;clrscr();ob.get_stdata();ob.get_ctmarks();ob.get_mstmarks();ob.put_stdata();ob.put_ctmarks();ob.put_mstmarks();ob.total();getch();}

Page 34: Class and object in C++ By Pawan Thakur

7-34 CLASSES AND OBJECTS

Output :

Here ‘student’ is the class from which we have derived ‘class_test’ class publicly. So thepublic members of the ‘student’ class will become public members of the ‘class-test’class. From ‘class_test’ class and ‘MST’ class we have derived ‘performance’ classpublicly. So the protected and public members of these classes will become protected andpublic members of the ‘performance’ class respectively. Private members will not beinherited.

A computer cannot do anything by its own. It must be introduced to do a desired job so itis necessary to specify a sequence of instructions that a computer must perform to solvea problem. Such a sequence of instructions written in a language that can be understoodby a computer is called a computer program. It is the program that controls the activity ofprocessing by the computer, and the computer performs precisely what the programwants it to do. The term software is the set of computer programs and procedures andassociated documents (flow charts, manuals, etc.), which describe the programs, andhow they are to be used.

A software package is a group of programs, which solve a specific problem for example,a word processing package may contain programs for text editing, text formatting, drawinggraphics, spelling checking etc.

Page 35: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-35

Introduction. Communicating with computers is not easy. They support some specialinstructions that are detailed defined. So it would be easy and simple to write program inenglish for communication. By using programms we are able to tellk the computer. Foran example if we want to know the total employer of CS dept. Than we could tell thecomputers, “check the all employee of CS dept and than me tell the total” and thanmachine return our answer.

A brief history of C and C++ :

C++ is an object oriented programming language. Initially named ‘C with classes’, C++was developed by Bjarne Stroustrup at AT and T Bell laboratories in the early eighties.C++ is an extension of C with a major addition of the class construct features.

Some of the most important features that C++ adds on to C are classes, functionoverloading and operator overloading. These feature enable developers to create abstractclasses, inherit properties from existing classes and support polymorphism.

C++ is a versatile language for handling very large programs it is suitable for virtually anyprogramming task including development of editors, compilers, data bases, communicationsystems and any complex real-life application systems.

POINTS TO REMEMBER(i) Class is a collection of member data and member function.

(ii) Class works as a uses defined data type.

(iii) Object is an instance of class.

(iv) Constructor is used to initialize the object of a class.

(v) Destructor is used to destroy the object created by the constructor uses ~ sign.

(vi) Inheritance is the process of accuring the properties of one class into anotherclass.

(vii) Inheritance provides the concept of reusability.

(viii) Private member of class cannot be inherited either is public mode or is privatemode.

(ix) In multi level inheritance, the constructors are executed is the order of inheritance.

(x) In multiple inheritance the base classes an constructed is the order is which theyappear is the declaration of the derived class.

KEY TERMS❍ Member function ❍ Constructor❍ Destructor overloading ❍ Inheritence❍ Class object ❍ Class member❍ Overloading ❍ Unary operator

Page 36: Class and object in C++ By Pawan Thakur

7-36 CLASSES AND OBJECTS

MULTIPLE CHOICE QUESTIONS1. To giving such special meaning to an operator is known as

(a) Operator precedence (b) Operator overloading(c) (a) and (b) (d) None of above

2. We can overload all the C++ operators except the class member access operators(a) Scope resolution operator and Size of operator(b) Conditional operator(c) (a) and (b)(d) Assignment operator

3. Friend function will have only one argument for(a) Unary operators (b) Binary operators(c) A and B (d) None of above

4. Friend function will have two argument for(a) Unary operators (b) Binary operators(c) (a) and (b) (d) None of above

5. A member function has one argument for(a) Unary operators (b) Binary operators(c) Conditional operators (d) None of above

6. A binary operator is an operator that performs its operation on(a) One operand (b) Two operand(c) (a) and (b) (d) None of above

7. The addition operator (+) is an example of(a) Binary operators (b) Unary operators(c) (a) and (b) (d) None of above

8. The keyword followed by the operator to overload operator is(a) Operator (b) Load(c) ~ (d) ++

9. In inheritance the new classes called derived classes are created from existingclasses called.(a) Base classes (b) Old class(c) Parent class (d) All of above

10. The accessibility levels and the way of derivation can be(a) Private (b) Protected and Public(c) (a) and (b) (d) None of above

11. The default accessibility mode is(a) Private (b) Protected and Public(c) (a) and (b) (d) None of above

Page 37: Class and object in C++ By Pawan Thakur

CLASSES AND OBJECTS 7-37

12. Deriving only one new class from single base class is called(a) Multiple inheritance (b) Single inheritance(c) Hybrid inheritance (d) Multi- label inheritance

13. Deriving only one new class from multiple base classes is called(a) Single inheritance (b) Hybrid inheritance(c) Multi- label inheritance (d) Multiple inheritances

14. Deriving two or more classes from single base class. and in turn each of thederived classes can further be inherited in the same way.(a) Multiple inheritance (b) Single inheritance(c) Hybrid inheritance (d) Multi- label inheritance

15. Combine two more types of inheritances, the resultant inheritance is called(a) Hierarchical inheritance (b) Single inheritance(c) Hybrid inheritance (d) Multi- label inheritance

16. A tree of classes which is rooted at single class is called(a) Hierarchical inheritance (b) Single inheritance(c) Hybrid inheritance (d) Multi- label inheritance

ANSWERS1. (b) 2. (c) 3. (a) 4. (b) 5. (b)6. (b) 7. (a) 8. (a) 9. (a) 10. (c)

11. (a) 12. (b) 13. (d) 14. (d) 15. (c)16. (a)

UNSOLVED QUESTIONS1. What do you mean by constructor ?

2. What are the copy constructor ?

3. Explain deferent constructor ?

4. Explain the properties of constructor and define destructor ?

5. What do you mean by inheritance is C++ ?

6. Explain different form of inheritance with example.

7. How do the properties of the following two derived from classes different ?

(a) Class D1 : Provate B {//...};

(b) Class D2 : Public B {//...};

8. Write a program to generate a series of fibonaci number using a copy constructorwhere the copy constructor is defined within the class declaration itself.

9. How does an array of class objects declared with multiple inheritance ?

Page 38: Class and object in C++ By Pawan Thakur

7-38 CLASSES AND OBJECTS

10. Explain the following with syntacture rules :

(i) Public inheritance (ii) Private inheritance

(iii) Protected inheritance.

11. What is overloading ? Explain operator overloading with example.

❍ ❍ ❍