Class and object in C++ By Pawan Thakur
Upcoming SlideShare
Loading in...5
×
 

Class and object in C++ By Pawan Thakur

on

  • 134 views

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 ...

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.

Statistics

Views

Total Views
134
Views on SlideShare
134
Embed Views
0

Actions

Likes
1
Downloads
17
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Class and object in C++ By Pawan Thakur Class and object in C++ By Pawan Thakur Document Transcript

  • 7.1. INTRODUCTION Classesextendthebuilt-incapabilitiesofC++ableyouinrepresentingandsolvingcomplex, 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
  • 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 can contain members, that can be either data or function declarations, or optionally access specifiers.All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access 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 other members of the same class or from their friends. (b) Protected members-: Protected members are accessible from members of their same 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 is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. The program 7.1 demonstrates the concept of class. Example 7.1.Aclass 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 of type int x, y and z with private access because private is the default access level. Two member functions with public access: getxy() and getsum() and their definition.
  • CLASSES AND OBJECTS 7-3 7.1.1. Class Objects An object is an individual instance of a class object is a variable of type class. You define an 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 integer demo 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 whose class 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 Members Once you define an actual object for class for example, ob for demo class. We can use the dot operator (.) to access the members of that object. The program 7.3 display the example of access the member of class, in this example we are calling getxy() and getsum() functions of demo class.
  • 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 comments getch(); } Output-: 7.1.3.Defined Member Function We 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 member function is to replace the function declaration by the actual function definition inside the class. The program 7.4 shown in the below, illustrates how to define a member function inside the class definition.
  • 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"; else cout<<"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 a member function is to replace the function declaration by the actual function definition outside the class. The program 7.5 shown in the below only members of rect that we
  • 7-6 CLASSES AND OBJECTS cannot access from the body of our program outside the class are x and y, since they have private access and they can only be referred from within other members of that same 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 class x = 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 operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself. You may notice that the definition of the member function area() has been included directly within the definition of the CRectangle class given its extreme simplicity, whereas set_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 are defining a function that is a member of the class CRectangle and not a regular global function.
  • CLASSES AND OBJECTS 7-7 The scope resolution operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, in the function set_values() of the previous code, we have been able to use the variables x and y, which are private members of class CRectangle, which means they are only accessible from other members of their class. 7.2. CONSTRUCTOR A constructor is a 'special' member function whose task is to initialize the object of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor is a ‘special’ member function which initializes the object of its 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 an object 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 members m ands n to zero. There is no need to write any statement to invoke the constructor function as we do with the normal member functions. 7.2.1. Properties of Constructor The 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
  • 7-8 CLASSES AND OBJECTS 3. They do not have return types, not even void. Therefore, they cannot return values. 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 Constructor If you do not declare any constructors in a class definition, the compiler assumes the class 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 declare objects of this class by simply declaring them without any arguments:
  • CLASSES AND OBJECTS 7-9 7.2.3.Parameterized Constructors We 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 objects with different values when they are created C++ permits us to achieve this objective by passing arguments to the constructor function when the subjects are created. The constructors that can take arguments are called parameterized constructors. 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
  • 7-10 CLASSES AND OBJECTS Here we have declared a constructor that takes two parameters of type int. Therefore the following 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 your own. It provides three special member functions in total that are implicitly declared if you do not declare your own. These are the copy constructor, the copy assignment operator, and the default destructor. 7.2.4.Copy Constructor A copy constructor takes a reference to an object of the same class as itself as an argument. A copy constructor is used to declare and initialize an object from another object. For example, the statement integer obj1(obj2); Would define the object obj2 and at the same 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 statement is legal and simply assigns the values of obj1 to obj2, member by member. This is task of the overloaded assignment operator (=).The program 7.8 displays the example of copy constructors. 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
  • 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:
  • 7-12 CLASSES AND OBJECTS 7.3. DESTRUCTOR Like a constructor, the destructor is a member function whose name is the same as the class name but it is preceded by a 'tilde' ~ sign. A destructor is a member function used to destroy the objects that have been 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 invoked implicitly by the complier upon exit from the program (or block or function as the case may be) to clean up storage, that is, no longer accessible. It is a good practice to declare destructors in a program. Since it releases memory for future use. Whenever ‘new’ is used 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 1n"; L
  • CLASSES AND OBJECTS 7-13 alpha A5 ; } cout << "n enter block 2n"; alpha A6; getch(); } Output: 7.4. OVERLOADING Overloading is one of the many exciting features of C++ language. It is an important technique that has enhanced the power of extensibility of C++. This feature of C++ help to write general function to perform more than one task with signal function name. 7.4.1. Function Overloading C++ permits the use of more than one functions with the same name. However such functions essentially have different argument list. The difference can be in terms of number or type of arguments or both. This process of using two or more functions with the same name but differing in the signature is called function overloading. But overloading of functions with different return types are not allowed. In overloaded functions, the function call determines which function definition will be executed. The biggest advantage of overloading is that it helps us to perform same operations on different data types without having the need to use separate names for each version. The program 7.10 displays the example of function overloading.. L
  • 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); }
  • 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 Overloading We know that C++ tries to make the user defined data types behave in much the same way 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 that C++ 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 known as “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 Overloading Although it looks simple to redefine the operators, there are certain restrictions and limitations 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 defined type. (3) We cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus (+) operator to subtract one value from the other. (4) There are some operators that can not overloaded like ., *, ::, ? : L
  • 7-16 CLASSES AND OBJECTS (5) We cannot use friend functions to overload certain operators. However, member functions can be used to overload them. Operators like, = (assignment operator),() Function call operator ,[ ] (subscripting operator ) and - > (class member access operator). The program 7.11 displays the example to overload greater than (>) sign to compare two strings 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 ; else return 0 ; } void main() { over S1, S2; S1.getdata(); S2.getdata(); if(S1>S2) cout<<"the first string is bigger:"; else cout<<"second string is bigger:"; getch () ; }
  • CLASSES AND OBJECTS 7-17 Output-: 7.4.4. Unary Operator Overloading A unary operator is an operator that performs its operation on only one operand. For Example, the increment operator is a unary operator. It operates on only one object. Use the keyword operator, followed by the operator to overload. Unary operator functions do not take parameters, with the exception of the postfix increment and decrement, which take an integer as a flag. The program 7.12 displays the example to overload unary minus operator. 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 operator void 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;
  • 7-18 CLASSES AND OBJECTS clrscr(); obj.input(); cout<<"nBefore overloadingn"; obj.show(); -obj; //Calling operator function cout<<"nAfter overloadingn"; obj.show(); getch(); } Output-: 7.4.5. Binary Operator Overloading An operator is referred to as binary if it operates on two operands. For Example, the addition operator (+) is a binary operator, where two objects are involved. Binary operators are created like unary operators, except that they do take a parameter. The parameter is a constant reference to an object of the same type. The program 7.13 displays the example to 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() {
  • CLASSES AND OBJECTS 7-19 cout<<"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; // overloading getch() ; } 7.5. DERIVED CLASS DECLARATION Derived classes are supersets of their base classes. Typically, a base class will have more than one derived class. Classes that are derived from others inherit all the accessible members of the base class. That means if a base class includes a member A and we derive it to another class with another member called B, the derived class will contain both members A and B. In order to derive a class from another, we use a colon (:) in the declaration of the derived class 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. The accessibility mode is optional and, if present, may be either private or public. The default accessibility mode is private. Accessibility mode specifies whether the features of the base class are privately derived or publicly derived. The program 7.14 displays the example of derived class. Program 7.14. Example of derived class #inclue<iostream.h> #include<conio.h> class Base
  • 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(); }
  • CLASSES AND OBJECTS 7-21 Output: In the above example, the derived class is Deived and the base class is Base. 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 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 the data members inherited from the base class Base and space is additionally allocated for the data members defined in the derived class Deived. The base class constructor Base is used to initialize the base class data members and the derived class constructor Deived is used 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 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. The mechanism of deriving a new class form the base class is called inheritance. 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. The derived class can inherit some or all the properties of the base class and can also pass on the inherited properties to the class which will be inherited from it. It depends on the accessibility level of the data and functions of the base class and the way the base class is L
  • 7-22 CLASSES AND OBJECTS inherited. The accessibility levels and the way of derivation can be- Private, Protected and Public. Fig. 7.1. Type of accessibility Modes. From the above Fig. 7.1 it is clear that only the Protected and Public members are inherited and not the Private members. And inherited members will be available for further inheritance only if they are inherited in public way or protected way otherwise not. 7.6.1. Features or Advantages of Inheritance (a) 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. (b) 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. (c) Reliability. Increases Program Structure which results in greater reliability. 7.6.2. Types OF Inheritance There 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 class is called single inheritance as shown in Fig. 7.2.
  • 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 the example 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;
  • 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 from person privately. The private members of the ‘person’ class will not be inherited. The public members of the ‘person’ class will become private members of the ‘student’ class since the type of the derivation is private. Since the inherited members have become private 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 base classes is called multiple inheritances as shown in Fig. 7.3.
  • 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.16 displays 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()
  • 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 inherited from all three classes privately. The members of the base classes have been declared as protected. They will become private members of the ‘D’ class since the type of the derivation is private. Since the inherited members have become private they can not be accessed by the object of the ‘D’ class. 3. Multi level inheritance. The process of deriving only one new class from the class that has 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 any number 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:
  • CLASSES AND OBJECTS 7-27 void 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;
  • 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 the public members of the ‘person’ class will become public members of the ‘student’ class
  • 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 of the ‘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 all these members will be inherited by the ‘performance’ class. But the private members will not be inherited. 4. Hierarchical inheritance. The process of deriving two or more classes from single base class. And in turn each of the derived classes can further be inherited in the same way as shown in Fig. 7.5. Thus it forms hierarchy of classes or a tree of classes which is rooted at single class. Fig. 7.5. Hierarchical Inheritance. HereAis the base class from which we have inherited two classes B and C. From class B we have inherited D and E and from C we have inherited F and G. Thus the whole arrangement forms a hierarchy or tree that is rooted at classA. The program 7.18 displays the 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;
  • 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()
  • 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 :
  • 7-32 CLASSES AND OBJECTS Here ‘person’ is the base class from which ‘student’ and ‘faculty’ classes have been derived privately so the public members of the ‘person’ class will become private members of 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 resultant inheritance 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:
  • CLASSES AND OBJECTS 7-33 void 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(); }
  • 7-34 CLASSES AND OBJECTS Output : Here ‘student’is the class from which we have derived ‘class_test’class publicly. So the public 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’ class publicly. So the protected and public members of these classes will become protected and public members of the ‘performance’ class respectively. Private members will not be inherited. A computer cannot do anything by its own. It must be introduced to do a desired job so it is necessary to specify a sequence of instructions that a computer must perform to solve a problem. Such a sequence of instructions written in a language that can be understood by a computer is called a computer program. It is the program that controls the activity of processing by the computer, and the computer performs precisely what the program wants it to do. The term software is the set of computer programs and procedures and associated documents (flow charts, manuals, etc.), which describe the programs, and how 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, drawing graphics, spelling checking etc.
  • CLASSES AND OBJECTS 7-35 Introduction. Communicating with computers is not easy. They support some special instructions that are detailed defined. So it would be easy and simple to write program in english for communication. By using programms we are able to tellk the computer. For an example if we want to know the total employer of CS dept. Than we could tell the computers, “check the all employee of CS dept and than me tell the total” and than machine 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, function overloading and operator overloading. These feature enable developers to create abstract classes, inherit properties from existing classes and support polymorphism. C++ is a versatile language for handling very large programs it is suitable for virtually any programming task including development of editors, compilers, data bases, communication systems 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 another class. (vii) Inheritance provides the concept of reusability. (viii) Private member of class cannot be inherited either is public mode or is private mode. (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 they appear is the declaration of the derived class. KEY TERMS ❍ Member function ❍ Constructor ❍ Destructor overloading ❍ Inheritence ❍ Class object ❍ Class member ❍ Overloading ❍ Unary operator
  • 7-36 CLASSES AND OBJECTS MULTIPLE CHOICE QUESTIONS 1. 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 existing classes 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
  • 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 the derived 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 ANSWERS 1. (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 QUESTIONS 1. 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 constructor where the copy constructor is defined within the class declaration itself. 9. How does an array of class objects declared with multiple inheritance ?
  • 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. ❍ ❍ ❍