Sei sulla pagina 1di 35

Unit-I Benefits of OOP

OOP offers several benefits to both the program designer and the user. The principal advantages are: Through inheritance, we can eliminate redundant code and extend the use of existing. Classes The principle of data hiding helps the programmer to build secure programs. It is possible to have multiple instances of an object to coexist without any interference. It is possible to map objects in the problem domain to those in the program. It is easy to partition the work in a project based on objects. Object oriented systems can be easily upgraded from small to large systems. We can build programs from the standard working modules that communicate with one another. This leads to saving of development time and higher productivity. Software complexity can be easily managed.

Applications of OOP
The most popular application of object oriented programming is the area of user interface design such as windows. Using the OOP techniques, hundreds of windowing systems have been developed. The promising areas for application OOPs are: Real time systems Simulation and modeling Object oriented databases Hypertext, hypermedia and expertext AI and expert systems Neural networks and parallel programming Decision support and office automation systems CIM/CAM/CAD systems

C++ keywords

auto bool break case catch char class extern new static_cast

delete do double dynamic_ cast else enum explicit namespace static union

friend goto if inline int long mutable sizeof typename

protected public register

switch template this

using virtual void volatile wchar_t while const false operator

reinterpret_cast throw return short signed typeid continue true try typedef const_cast float

Applications of C++
C++ is a versatile language for handling very large programs. It is suitable for virtually any programming tasks including development of editors, compilers, databases, communication systems and any complex real life application systems. C++ allows creating hierarchy related objects. C++ is able to map the real world problem properly. C++ programs are easily maintainable and expandable.

Defining Member Functions


The declared member functions in the class can be defined in two places. i. ii. Outside Class definition Inside Class definition

In both case the function body is identical but difference in the way of function header is defined. Outside Class definition The member functions declared inside of a class are defined separately in the outside of the class. An important difference between a member function and a normal function is that a member function have a membership identity label in the header .This label tells the compiler which class the function belongs to. Syntax for member function definition returntype classname :: functionname(parameter list) { body of the function }
The scope resolution operator (::) in c++ used to define the already declared in the member functions of the class.

Example #include <iostream.h> #include <conio.h> class person { Char name[30]; int age; public: void getdata (); void display (); };

//declaration

Void person :: getdata () //definition outside the class { cout << "Enter name: " ; cin>>name; cout << "\nEnter age: " ; cin>>age; } Void person :: display () //definition outside the class { cout << "\nName: "<<name; cout << "\nAge: " <<age; } void main () { Person p; p.getdata(); p.display(); return 0; } Output of the program Enter name:Krishna Enter age:20 Name:Krishna Age:20 Characteristics of the member function Member functions can access the private data of the class. A member function can call another member function directly, without using the dot operator. Several different classes can use the same function name. The membership label will resolve their scope. Inside Class definition In this method, the functions are defined in the place of the function declaration. Normally, only small functions are defined inside the class definition. When a function is defined inside a class, it is treated as an inline function. #include <iostream.h> #include <conio.h> class person {

Char name[30]; int age; public: void getdata () //definition inside the class { cout << "Enter name: " ; cin>>name; cout << "Enter age: " ; cin>>age; } Void display () //definition inside the class { cout << "Name: "<<name; cout << "Age: " <<age; } }; void main () { Person p; p.getdata(); p.display(); return 0; } Output of the program Enter name:Krishna Enter age:20 Name:Krishna Age:20

Nesting of Member functions


A member functions can be called by using its name inside another member function of the same class. This is known as nesting of member functions. Example #include <iostream.h> #include <conio.h> class person { Char name[30]; int age; public: void getdata (); void display (); };

Void person :: getdata () { cout << "Enter name: " ; cin>>name; cout << "Enter age: " ; cin>>age; display(); //calling another member function } Void person :: display () { cout << "Name: "<<name; cout << "Age: " <<age; } void main () { Person p; p.getdata(); return 0; } Output of the program Enter name:Krishna Enter age:20 Name:Krishna Age:20 The program contains two functions are getdata( ) and display( ). The main function calls only the getdata( ) function and inside of these function, the display( ) function is called.

Static Data Member


Classes can contain static member data and member functions. When a data member is declared as static, only one copy of the data is maintained for all objects of the class. A data member is made static by prefixing the data member declaration within the class body with the keyword static Syntax static datatype variable; Example static int count; A static data member acts as a global object that belongs to its class type. Unlike other data members where each class object has its own copy, there is only one copy of a static

data member per class type. A static data member is a single, shared object accessible to all objects of its class type. #include< iostream.h> #include< conio.h> class item { private: static int count; int number; public: void getdata(int a) { number=a; count ++; } void getcount() { cout< < "Count:"< < count; } }; int item::count; void main() { item a, b; a.getcount(); b.getcount(); a.getdata(100); b.getdata(200); cout< < After reading data; a.getcount(); b.getcount(); } OUTPUT Count: 0 Count: 0 After reading data Count: 2 Count: 2

The program class item has a static data member count. Before the getdata() function is called by the both the objects a and b, the count data member values of both objects are 0. After the getdata() function is called by the both the objects a and b, the count data member values is increased by 2 for both objects because of the count value shared by all the objects in the class.

Constructors
Constructors are special member functions of classes that are used to construct class objects. Construction may involve memory allocation and initialization for objects. Its name is same as that of its class name. It is invoked when an object of that class is created. When an object of a class is created, C++ calls the constructor for that class. If no constructor is defined, C++ invokes a default constructor, which allocates memory for the object. A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. syntax class username { -------public: username (); --------------}; username:: username () { ------------} Example #include <iostream.h> #include <conio.h> class sum { int x,y ; public:

// constructor declaration

// constructor definition

sum (); int add (void) { return (x+y); } }; sum::sum() { x = 10; y = 10; }

// constructor declaration

// constructor definition

int main () { sum s1; cout << "Total: " << s1.add( ) ; return 0; } Output of the program Total : 20 The above program has the class name sum and it has contains two functions are sum() and add(). The sum() function is the constructor function because it has same name of its class name. In the sum() function the values of the variables are intilalized. The constructor functions have some special characteristics as follows: 1. They should be declare in the public section. 2. They are invoked automatically when the objects are created. 3. They do not have return types not even void. 4. They cannot be inherited, though a derived class can call the base class constructor. 5. They can have default arguments. 6. We cannot refer to their address. 7. Constructors cannot be virtual. 8. An object with a constructor cannot be used as a member of a union.

Parameterized Constructors
The constructors that can take arguments are called Parameterized Constructors. syntax class username { -------public: username (int,int); ---------------

// constructor declaration

}; username:: username (int a, int b) // constructor definition { ------------} The initial values are passed as arguments to the constructor function when an object is declared. This can be done in two ways. By calling the constructor explicitly By calling the constructor implicitly

Example for explicit call sum s2=sum(20,30); This statement creates a sum object s2 and passes the values 20 and 30 to it. Example for implicit call sum s1(10,10); This method is the shorthand method to call the constructor function.

#include <iostream.h> #include <conio.h> class sum { int x,y ; public: sum (int,int); int add (void) { return (x+y);

// constructor declaration

} }; sum::sum (int a, int b) { x = a; y = b; } // constructor definition

int main () { sum s1(10,10); // constructor called implicitly sum s2=sum(20,30); // constructor called explicitly cout << "Total: " << s1.add( ) ; cout << "\nTotal: " << s2.add( ); return 0; } Output of the program Total : 20 Total : 50 The above program has the class name sum and it has contains two functions are sum(int,int) and add().In the constructor function sum(), the two variables are passed as arguments and the values of the variables are initialized.

Operating overloading
Operating overloading allows you to pass different variable types to the same function and produce different results. Syntax for overloading operators: return-type operator operatortype ( parameters ); returntype- the of value returned by the specified operation. operator -The keyword operator is used to overload the specified operator operatortype - the operator which has to be overloaded Operator functions must be either member function or friend function. The following set of operators is commonly overloaded for user-defined classes:

= (assignment operator) + - * (binary arithmetic operators) += -= *= (compound assignment operators)

== != (comparison operators)

The following operators are not used for operator overloading: :: ( scope resolution operator ) . ( member selection ) .* ( member selection through pointer to function ) sizeof ( size of operator ) ?: ( conditional operator ) The process of overloading involves the following steps 1. Create a class that defines the data type is to be used in the overloading operations. 2. Declare the operator function operator operatortype() in the public part of the class. 3. Define the operator function to implement the required operations. There are two types of operator overloading:

Unary operator overloading Binary operator overloading

Overloading unary operators


Unary operators are operators that act on a single operand. A unary operator can be overloaded as a non-static member function with no argument or as a global function with one argument. syntax for a nonstatic member function that overloads the operator: returntype operator unaryoperator () syntax for a nonmember function that overloads the operator: returntype operator unaryoperator (parameter) returntype - the of value returned by the specified operation. operator - The keyword operator is used to overload the specified operator unaryoperator - the unary operator which has to be overloaded. The following are the Unary operators:

&

++

--

->

->*

Example #include< iostream.h> #include< conio.h> class unary { private: int x,y,z; public: unary(void) { cout< < "Enter Any Three Integer Nos. : "; cin>>x>>y>>z; } void display(void) { cout< < " The Three Nos. Are : "< < x< < y< < z; } void operator -() { x = -x; y = -y; z = -z; } }; void main() { clrscr(); unary s; s.display(); -s; s.display(); //called operator-() function //unary operator function

getch(); } output Enter Any Three Integer Nos. : 4 -8 6 The Three Nos. Are : 4 -8 6 The Three Nos. Are : -4 8 -6 In the above program, unary minus operator is overloaded. The unary minus operator changes the sign of an operand when applied to basic data-type ( int, float, double etc. ). Before activating the operator function, the values of x, y and z are displayed as: x=4 y= -8 z=6

After execution of the statement (- s ; ) the operator function gets activated and the values of x, y and z are displayed as: x= -4 y=8 z= -6

Overloading Binary operators


Binary operators are operators that act on a two operands. A binary operator can be overloaded as a non-static member function with one argument or as a global function with two arguments syntax for a nonstatic member function that overloads the operator: returntype operator binaryoperator (parameter) syntax for a nonmember function that overloads the operator: returntype operator binaryoperator (parameters) returntype - the of value returned by the specified operation.

operator -The keyword operator is used to overload the specified operator binaryoperator - the binary operator which has to be overloaded. The following are the Binary operators:

+ - * / % ^ & | << >> += -= *= /= %= ^= &= |= <<= >>= < <= > >= == != && ||
Example #include<iostream.h> #include<conio.h> class complex { float x, y; public: complex() { } complex(float real,float imag) { x=real; y=imag; } void get(); void display(); complex operator+(complex); }; void complex::get() { cout<<"Enter the value of complex number"; cin>>x>>y; }

complex complex :: operator+(complex c) { complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex :: display() { cout<<x<<"+i"<<y; } int main() { clrscr(); complex c1,c2,c3; c1.get(); c2.get(); c3=c1+c2; cout<<"Resultant complex number:";c3.display(); getch(); return 0; } output Enter the value of complex number2.3 4.4 Enter the value of complex number3.5 1.5 Resultant complex number:5.8+i5.9 In the above program, Binary addition operator is overloaded. The + operator function adds two complex numbers and returns the resultant complex values. The following statement invokes the operator function. c3 = c1 + c2 ; // Invokes operator + ( ) function

INHERITANCE Defining Derived Class


Inheritance is the process of creating new classes from the existing class. The old class is referred to as the base class and the new class is called as derived class or subclass.
The general form of defining a derived class:

class derivedclass : accessspecifier baseclass { members of the derived class }; The colon (:) -indicates that the class derivedclassname is derived from the class baseclassname. The accessspecifier it may be public, private or protected.
There are three ways of deriving a new class from a base class:
class derived : public base {}; class derived : private base {}; class derived : protected base {};

Public inheritance When a derived class publicly inherits the base class, all the public members of the base class also become public to the derived class and the objects of the derived class can access the public members of the base class. Private inheritance When a derived class privately inherits a base class, all the public members of the base class become private for the derived class. protected inheritance The members declared as protected can be accessed by the member functions within their own class and any other class immediately derived from it. Advantages of Inheritance: Reusability: Inheritance helps the code to be reused in many situations. Saves Time and Effort. Increases Program Structure which results in greater reliability.

Single Inheritance
Deriving of a class from only one base class is called single inheritance. The representation of the single inheritance is shown in the following Fig. A

B The single inheritance is declared as follows: Class A { --------}; Class B : public A { --------}; A- Base Class B- Derived Class or Sub Class Example #include<iostream.h> #include<conio.h> class student { int roll; public: char name[20]; void get(); int getroll(); }; void student :: get() { cout<<"Enter Name"; cin>>name; // Base class

cout<<"\n Enter roll"; cin>>roll; } int student :: getroll() { return roll; } class test : public student { float m1 ,m2; public: void getmark(); void display(); }; void test :: getmark() { cout<<"\n Enter mark in Subject1:"; cin>>m1; cout<<"\n Enter mark in Subject2:"; cin>>m2; } void test :: display() { cout<<"\nName:"<<name; cout<<"\nRoll:"<<getroll(); cout<<"\nMark in Subject1:"<<m1; cout<<"\nMark in Subject2:"<<m2; } void main() { clrscr(); // derived class

test t; t.get(); t.getmark(); t.display(); getch(); } output Enter NameRama Enter roll107 Enter mark in Subject1:89 Enter mark in Subject2:90 Name:Rama Roll:107 Mark in Subject1:89 Mark in Subject2:90 The program has a base class student and a derived class item. The class student contains one private data member, one public data member and two member functions. The class test contains two private data members and two member functions. The class test is publically derived the base class student. Thus a public member of the base class student is inherited by the derived class test. The private members of the student cannot be inherited by test.

Multiple Inheritance
Deriving a class from more than one base class is called as multiple inheritance. The representation of the multiple inheritance is shown in the following Fig.

C
syntax: class Subclass : accessspecifier Baseclass1, accessspecifier Baseclass2, accessspecifier Baseclassn { members of the derived class ; };

The multiple inheritance is declared as follows: Class A { --------}; Class B { --------}; Class C : public A, public B { --------};
Example

#include<iostream.h> #include<conio.h> class student { int roll; public: char name[20]; void get(); int getroll(); }; void student :: get() { cout<<"Enter Name"; cin>>name; cout<<"\n Enter roll"; cin>>roll; } int student :: getroll() {

return roll; } class test { public: float m1 ,m2; void getmark();

}; void test :: getmark() { cout<<"\n Enter mark in Subject1:"; cin>>m1; cout<<"\n Enter mark in Subject2:"; cin>>m2; } class result :public student, public test { float total; public: void marks(); void display(); }; void result :: marks() { total=m1+m2; cout<<"\n Total marks:"<<total; } void result :: display() { cout<<"\nName:"<<name;

cout<<"\nRoll:"<<getroll(); cout<<"\nMark in Subject1:"<<m1; cout<<"\nMark in Subject2:"<<m2; } void main() { clrscr(); result r; r.get(); r.getmark(); r.display(); r.marks(); getch(); } output Enter NameRama Enter roll107 Enter mark in Subject1:89 Enter mark in Subject2:90

Name:Rama Roll:107 Mark in Subject1:89 Mark in Subject2:90 Total marks:179 In the program, the class student and the class test are serves as a base class for the derived class result. The class student and class test is publically derived by the class result. Thus a public member of the base classs student and test are inherited by the class result. The private members of the student and test cannot be inherited by test and result.

Hierarchical Inheritance:
Deriving of several classes from a single base class is called as hierarchical inheritance. The representation of the hierarchical inheritance is shown in the following Fig. A

The hierarchical inheritance is declared as follows: Class A { --------}; Class B : public A { --------}; Class C : public A { --------}; Class D : public A { --------}; Example #include<iostream.h> #include<conio.h> class student { int roll; public: char name[20]; void get(); void display();

}; void student :: get() { cout<<"\nEnter Name"; cin>>name; cout<<"\n Enter roll"; cin>>roll; } void student:: display() { cout<<"\nName:"<<name; cout<<"\nRoll:"<<roll; } class arts : public student { char sub1[20],sub2[20]; public: void get(); void display(); };

void arts :: get() { student :: get(); cout<<"\n Enter the Subject1:"; cin>>sub1; cout<<"\n Enter the Subject2:"; cin>>sub2; } void arts :: display() {

student :: display(); cout<<"\n Subject1:"<<sub1; cout<<"\n Subject2:"<<sub2; } class science : public student { char sub1[20],sub2[20]; public: void get(); void display(); }; void science :: get() { student :: get(); cout<<"\n Enter the Subject1:"; cin>>sub1; cout<<"\n Enter the Subject2:"; cin>>sub2; } void science :: display() { student :: display(); cout<<"\n Subject1:"<<sub1; cout<<"\n Subject2:"<<sub2; } void main() { clrscr(); arts a; cout<<"Enter the Details for arts students"; a.get();

a.display(); science s; cout<<"\nEnter the Details for science students"; s.get(); s.display(); getch(); } output Enter the Details for arts students Enter Name Rama Enter roll 107 Enter the Subject1:Accountancy Enter the Subject2:Banking Name:Rama Roll:107 Subject1:Accountancy Subject2:Banking Enter the Details for science students Enter Name Kannan Enter roll 303 Enter the Subject1:C++ Enter the Subject2:Network

Name:Kannan Roll:303 Subject1:C++ Subject2:Network In the program, the class student serves as a base class for the derived classes arts and science. The class arts and science are publically derived the base class student. Thus a public member of the base class student is inherited by the classs arts and science. The private members of the student cannot be inherited by arts and science.

Multilevel Inheritance:
Deriving of a class from another derived class is called as multilevel inheritance. The representation of the multilevel inheritance is shown in the following Fig.

A B C The multilevel inheritance is declared as follows: Class A { --------}; Class B : public A { --------}; Class C : public B { --------};
Example

#include<iostream.h> #include<conio.h>

class student { int roll; public: char name[20]; void get(); int getroll();

}; void student :: get() { cout<<"Enter Name"; cin>>name; cout<<"\n Enter roll"; cin>>roll; } int student :: getroll() { return roll; } class test : public student { public: float m1 ,m2; void getmark(); void display(); }; void test :: getmark() { cout<<"\n Enter mark in Subject1:"; cin>>m1; cout<<"\n Enter mark in Subject2:"; cin>>m2; } void test :: display() { cout<<"\nName:"<<name; cout<<"\nRoll:"<<getroll(); cout<<"\nMark in Subject1:"<<m1;

cout<<"\nMark in Subject2:"<<m2; } class result : public test { float total; public: void marks(); }; void result :: marks() { total=m1+m2; cout<<"\n Total marks:"<<total; } void main() { clrscr(); result r; r.get(); r.getmark(); r.display(); r.marks(); getch(); }

Enter NameRama Enter roll107 Enter mark in Subject1:89 Enter mark in Subject2:90 Name:Rama Roll:107 Mark in Subject1:89 Mark in Subject2:90 Total marks:179

In the program student serves as a base class for the derived class test and this test class is serves as a base class for the derived class result. The class test is publically derived the base class student and in the similar manner the class result is publically derived the base class test. Thus a public member of the base class student is inherited by the class test and result. The private members of the student cannot be inherited by test and result.

Hybrid Inheritance:
Hybrid Inheritance is a more than one form of inheritance. The representation of the hybrid inheritance is shown in the following Fig. A

D The above representation have more than one inheritance such as multiple inheritance, multilevel inheritance and hierarchical inheritance. Example
student sports test

result

#include<iostream.h> #include<conio.h> class student

{ int roll; public: char name[20]; void get(); int getroll(); }; void student :: get() { cout<<"Enter Name"; cin>>name; cout<<"\n Enter roll"; cin>>roll; } int student :: getroll() { return roll; } class test : public student {

public: float m1 ,m2; void getmark(); void display(); }; void test :: getmark() { cout<<"\n Enter mark in Subject1:"; cin>>m1; cout<<"\n Enter mark in Subject2:";

cin>>m2; } void test :: display() { cout<<"\nName:"<<name; cout<<"\nRoll:"<<getroll(); cout<<"\nMark in Subject1:"<<m1; cout<<"\nMark in Subject2:"<<m2; } class sports {

public: float score; void getscore(); void putscore(); }; void sports :: getscore() { cout<<"\n Enter score in sports:"; cin>>score;

} void sports :: putscore() { cout<<"\nScore:"<<score; } class result : public test,public sports { float total; public:

void marks(); }; void result :: marks() { total=m1+m2+score; cout<<"\n Total marks:"<<total; } void main() { clrscr(); result r; r.get(); r.getmark(); r.getscore(); r.display(); r.putscore(); r.marks(); getch(); }

output Enter NameRama Enter roll107 Enter mark in Subject1:89 Enter mark in Subject2:90 Enter score in sports:10 Name:Rama Roll:107 Mark in Subject1:89 Mark in Subject2:90 Score:10 Total marks:189

The programs have both multiple inheritance and multilevel inheritance. In the multilevel inheritance the class student serves as a base class for the derived class test and which serves as a base class for the class result. In the multiple inheritance the class result is derived from both of the classs sports and test The public member of the base class student is inherited by the classes test and result . The private members of the student cannot be inherited by test and result.

Potrebbero piacerti anche