You are on page 1of 55

BASIC CONCEPTS OF OOPS

OBJECTS CLASSES DATA ABSTRACTION AND ENCAPSULATION ; INHERITANCE POLYMORPHISM DYNAMIC BINDING INTRODUCTION TO C++ COMMENTS

Represented by // (double slash) OUTPUT OPERATOR
EG: cout<<” Hello india”; INPUT OPERATOR EG: cin>> number

REFERENCE VARIABLES SYNTAX: Data-type & reference-name = variable-name; Eg: Float total=100; Float & sum=total; MEMORY MANAGEMENT OPERATORS SYNTAX: Pointer-variable = new data-type; delete pointer-variable; CONTROL STRUCTURES SEQUENCE STRUCTURE SELECTION LOOP

• • • • • • • • • • • • • • • • •

DECLARATION OF A FUNCTION type function-name (argument-list); Eg: float volume(int x, float y, float z); FUNCTION DEFINITION return type function-name(argument-list) { …….. Function body; …….. } INLINE FUNCTIONS SYNTAX: Inline function-header { Function body; }

• • • • • • • • • • • • • • • • • •

SPECIFYING A CLASS 2 PARTS 1. CLASS DECLARATION 2. CLASS FUNCTION DEFINITIONS GENERAL FORM OF CLASS DECLARATION class class_name { private: Variable declarations; Function declarations; public: Variable declarations; Function declarations; }; CREATING OBJECTS class-name object-name; ACCESSING CLASS MEMBERS object-name.function-name (actual-arguments);

• • • • • • • • • • • • • • • • • • • • •

DEFINING MEMBER FUNCTIONS OUTSIDE THE CLASS DEFINITION SYNTAX: return-type class-name :: function-name(argument declaration) { Function body; } INSIDE THE CLASS DEFINITION SYNTAX: class class_name { private: Variable declarations; Function declarations; public: Variable declarations; return type function-name( argument list) //Inline function { Function body; } };

Class A class is a way to bind the data and its function together. It allows the data to be hidden from external use. - Speifying a class The general form of a class is, class class_name { private: variable declarations; function declaration; public: variable declarations; function declaration; }; }

• - Simple class example- Representation of a class • - Creating objects class- name objectname; • – Accessing class members objectname.function-name (actual parameters); • - Defining member functions both inside and outside the class. • Return-type class-name :: function-name (argument declaration) • { • Function body;

Abstraction
• • • Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost. Data is hidden from external access .

» Inheritance
• • Inheritance is the process by which objects of one class acquire the properties objects of another class. New class is derived from the existing class.

» Data encapsulation
• The wrapping up of data and functions into a single unit is known as data encapsulation. Here the data is not accessible to the outside world. The insulation of data from direct access by the program is called data hiding or

information hiding

.

Polymorphism
• Polymorphism is an important concept of OOPs. Polymorphism means one name, multiple forms. It is the ability of a function or operator to take more than one form at different instances

» Abstract class
• An abstract class is one that is not used to create objects. It is designed only to act as a base class to be inherited by other classes.

» Tokens
• The smallest individual units in a program are known as tokens. C++ has the following tokens keywords, identifiers , constants, strings and operators.

» Templates
• Templates enable us to define generic classes and functions and thus provides support for generic programming.

Objects

• Objects are the basic run-time entities in an object oriented system. Objects • may represent a person, a place, a bank account, a table of data or any item. • objects are variables of type class.



• • • • • • • • • • • • • • • • • • •

Array of Objects with an example
We can create arrays of variables that are of the type class. Such variables are called arrays of objects. Syntax: Class-name object-name[size]; Program to illustrate array of object #include<iostream.h> class employee { char name[30]; float age; public: void getdata(void); void putdata(void); }; void employee::getdata(void) { cout<<”enter name:”; cin>>name; cout<<”enter age”; cin>>age; }

• • • • • • • • • • • • • • • • • • • •

void employee::putdata(void) { cout<<”name:”<<name<<”\n”<<”age:”<<age<<”\n”; } const int size=3; int main() { employee mangaer[size]; for(int i=0; i<size; i++) { cout<<”\n details of manager”<<i+1<<”\n”; manager[i].getdata(); } for(i=0;i<size;i++) { cout<<”\n manager”<<i+1<<”\n”; manager[i].putdata(); } retrun 0; }

Inline functions
• • • • • • • • • • • • • • • • • An inline function is a function that is expanded in line when it is invoked. The compiler Replaces the function call with corresponding function code. The inline funcitions are defined As follows: inline function-header { Function body; } Example: inline double cube(double a) { Return(a*a*a); } Some situations where inline expansion may not work are: For functions returning values, if a loop , a switch, or a goto exists. For functions not returning values, if a return statement exists. If functions contain static variables. If inline functions are recursive.

• Static data member: • • It is initialized to zero when the first object is created and no other initialization is permitted. • • Only one copy of that member is created and shared by all the objects of that class. • • It is visible only within the class, but the life time is the entire program. • Static member functions: • • A static member function can access only other static members declared in the same class. • • It can be called using the class name instead of objects as follows, class_name :: function_name;

Types of opertors in C++
• . :: Scope resolution operator: • A variable declared in an inner block cannot be accessed outside the block. To resolve this problem the scope resolution operator is used. It can be used to uncover a hidden variable. This operator allows access to the global version of the variable. It takes the form, :: variable-nam • • • 2. ::* Pointer to member declarator : To declare a pointer to the member of the class 3. ->* Pointer to member operator : To access a member using object name and a pointer to that member

4. .* Pointer to member operator : To access a member using a pointer to the object and a pointer to that member • 5. delete Memory release operator : When a data object is no longer needed it is destroyed to release the memory space for reuse.

• 6. new Memory allocation operator : The new operator can be used to create objects of any data-type. It allocates sufficient memory to hold a data object of type data-type and returns the address of the object. • 7. endl Line feed operator : causes a linefeed to be inserted • 8. setw Field width operator : provides a common field width for all the numbers and forces them to be printed right justified

• • • • • • • • • • • • • • • •

» Function Overloading – Example Program #include<iostream.h> #include<conio.h> void swap(int &x,int &y) { int t; t=x; x=y; y=t; } void swap(float &p,float &q) { float t; t=p; p=q; q=t; }

• • • • • • • • • • • • • • • • • • • • •

void swap(char &c1,char &c2) { char t; t=c1; c1=c2; c2=t; } void main() { int i,j; float a,b; char s1,s2; clrscr(); cout<<"\n Enter two integers : \n"; cout<<" i = "; cin>>i; cout<<"\n j = "; cin>>j; swap(i,j); cout<<"\n Enter two float numbers : \n"; cout<<" a = ";

• • • • • • • • •

cin>>a; cout<<"\n b = "; cin>>b; swap(a,b); cout<<"\n Enter two Characters : \n"; cout<<" s1 = "; cin>>s1; cout<<"\n s2 = "; cin>>s2;

• • • • • • • •

swap(s1,s2); cout<<"\n After Swapping \n"; cout<<"~~~~~~~~~~~~~~~~\n"; cout<<" \n Integers i = "<<i<<"\t j = "<<j; cout<<" \n Float Numbers a= "<<a<<"\t b = "<<b; cout<<" \n Characters s1 = "<<c1<<"\t c2 = "<<s2; getch(); }

Constructor
• • Constructor is a special member function whose task is to initialize the objects of its class. It’s name is same as the class name. It constructs values of data members of the class. Class integer { Int m, n; Public: Integer(void); ----}; Integer :: integer(void) { M=0; n=0; } When an object is created, it binds the function with the object as soon as its created. Its invoked as follows: Integer int1

• • • • • • • • • • • •

» overloaded constructor
• • • • • • • • • • • • • • • The usage of all the constructors in a program like parameterized constructor, copy constructor and constructor with default arguments are used in the same program- overloaded constructor. -Program to illustrate an overloaded constructor. #include<iostream.h> class code { int id; public: code() { } code(int a) { id=a; }

• • • • • • • • • • • • • • • • • • •

code(code &x) { id=x.id; } void display(void) { cout<<id; } }; int main() { code A(100); code B(A); code C=A; cout<<"\n id of A: ";A.display(); cout<<"\n id of B: ";B.display(); cout<<"\n id of C: ";C.display(); return 0; }

PROGRAM TO ILLUSTRATE DYNAMIC CONSTRUCTOR
#include<iostream.h> #include<string.h> Class STRING { char *name; int len; public:STRING() { len=0; name=new char[len+1]; } STRING(char *str) { len=strlen(str); name=new char[len+1]; strcpy(name,str); } void display() { cout<<name<<endl; }

void concat(STRING &s1, STRING &s2) { len=s1.len+s2.len; delete name; name= new char[len+1]; strcpy(name,s1.name); strcpy(name,s2.name); } } int main() { STRING s1(“hello”); STRING s2(“world”); STRING s3; s3.concat(s1,s2); s3.display(); }

» Destructor • A destructor is used to destroy the objects that have been created by a constructor. Like the constructor the destructor is a member function whose name is same as the class name but is • Preceded by a tilde. • Eg: ~integer( ) { } • Destructor never takes any argument nor does it return any value. • It will be invoked implicitly by the compiler upon exit from the program( or bloc or function) • Program to illustrate destructor • #include<iostream.h> • class fib • { • int f0,f1,fib; • public: • fib(); • ~fib(); • void getdata();

• • • • • • • • • • • • • • • • • • • • • • •

void display(); void showdata(); }; fib::fib() { f0=0; f1=1; fib=f0+f1; } fib::~fib() { cout<<"memory space deleted"; } void fib::getdata() { f0=f1; f1=fib; fib=f0+f1; } void fib::showdata() { cout<<f0<<endl<<f1<<endl<<fib<<endl; }

• • • • • • • • • • • • • • • •

void fib::display() { cout<<fib<<endl; } int main() { fib f; int i; f.showdata(); for(i=0;i<=5;i++) { f.getdata(); f.display(); } return(0); }

FRIENDLY FUNCTIONS
C++ allows common function to be made friendly with both classes thereby allowing the function to have access to private data of these classes.  Such a function need not be a member of any of these classes.  TO MAKE AN OUTSIDE FUNCTION FRIENDLY class ABC { ……… public: …….. friend void xyz(void); }

• Example #include class sample { int a,b; public: void setvalue( ){a=25; b=40;} friend float mean(sample s); }; float mean(sample s) { return float(s.a+s.b)/2.0; } int main( ) { sample x;

x.setvalue( ); Cout<<“ mean value =“<<mean(x)<<“\n”; return 0; }   Member functions of one class can be made friend of another class In such cases they are defined using scope resolution operator class x { ….. int fun1( ); }; class y

//member function of x

{ ……… friend int x :: fun1( ); //fun1( ) of x is friend of y };

All the member functions of one class is declared as a friend to another class ---- This class is called friendly class. • Specified as follows: class z { ……. friend class x; //All the member functions of x are friends to z };

FUNCTION FRIENDLY TO TWO CLASSES class ABC; class XYZ { int x; public: void setvalue(int i){x=i;} friend void max( XYZ,ABC); }; class ABC { int a; public: void setvalue(int i) { a=i;} friend void max(XYZ,ABC); };

void max( XYZ m , ABC n) { if (m.x >= n.a) cout<<m.x; else cout<<n.a; } int main( ) { ABC abc; abc.setvalue(10); XYZ xyz; xyz.setvalue(20); max(xyz,abc); return 0; }

• • • •

Friend functions can be called by reference also. Here local copies of objects are not made. Instead a pointer to the address of object is passed and function works directly on actual objects. This method alters the private members – This is against Data hiding concept EXAMPLE

# include<iostream.h> class class_2; Class class_1 { int value1; public: void indata(int a){value1=a;} void display(void){ cout<<value1<<“\n”;} friend void exchange(class_1 &, class_2 &); };

class class_2 { int value2; public: void indata(int a){value2=a;} void display(void){ cout<<value2<<“\n”;} friend void exchange(class_1 & , class_2 &); }; void exchange(class_1 & , class_2 &) { int temp=x.value1; x.value1=y.value2; y.value1=temp; }

int main( ) { class_1 c1; class_2 c2; c1.indata(100); c2.indata(200); cout<<“values before exchange”<<“\n”; c1.display(); c2.display( ); exchange(c1,c2); // Swapping cout<<“values after exchange”<<“\n”; c1.display( ); c2.display( ); return 0; }

»Operator overloading
• Operator overloading provides a flexible option for the creation of new definitionsfor most of the c++ operators. » Rules : • • Only existing operators can be overloaded. • • We cannot change the basic meaning of an operator. • • The overloaded operator must have at least one operand. • • Overloaded operators follow the syntax rules of the original operators. • • There are some operators that can not be overloaded (sizeof , . , .*, :: and ?:) • • We cannot use friend function to overload certain operators( =, (), [], ->)


• • • • • • • • • • • • • • •

Operator overloading using friend function
-General form of operator function is: Return type classname :: operator (op-arglist) { Function body } Overloaded operator functions can be invoked by expression x op y for binary operators In the following program overloaded function is invoked when the expression c1+c2 is encountered. This expression is the same as operator op(x,y) (ie) operator +(c1,c2) using friend function #include<iostream.h> #include<conio.h> class complex { private: float real;

• • •

float img; public: complex()

• • • • • • • • • • • • • • • • • •

{ real=0.0; img=0.0; } complex(float a,float b) { real=a; img=b; } friend complex operator +(complex,complex); void display() { cout<<"\n"<<real<<"+-i"<<img<<"\n"; } }; complex operator +(complex c1,complex c2) { complex t;

• • • • • • • • • • • • • • • •

t.real=c1.real+c2.real; t.img=c1.img+c2.img; return(t);} //}; void main() { clrscr(); complex c1(5.5,2.5); complex c2(1.5,5.5); complex c3; c3=c1+c2; c1.display(); c2.display(); c3.display(); getch(); }

Overloading assignment operator
• • • • • • • • • • • • • • • • • #include<iostream.h> #include<conio.h> class assignment { private: int x; public: assignment() { } assignment(int y) { x=y; } assignment operator =(assignment as) { x=as.x;

• • • • • •
• • • • • • • • • •

return(x); } void print() { cout<<"x = "<<x; }
}; void main() { clrscr(); assignment a(100); assignment b; b=a; b.print(); getch(); }

Inheritance
• The mechanism of deriving a new class from an old class is called inheritance. The old class is refered to as the base class and new one is called as the derived class or sub class. The various types of inheritance are, • Single inheritance • Multi-level inheritance • Multiple inheritance • Hierarchical inheritance • Hybrid inheritance

• • • • • •

Multilevel Inheritance
• • • • • • • • • • • • • • • • • • • class B is derived from class A and class C is further derived from the derived class B. Class A{….}; //Base class Class B: public A{….}; //B derived from A Class C: public B{…..}; //C derived from B #include <iostream.h> Class student { Protected: Int rollnumber; Public: Void getnumber(int); Void putnumber(void); }; Void student::getnumber(int a) { Rollnumber=a; } Void student::putnumber() {

• • • • • • • • • • • • • • • • • • • • • • •

Cout<<”roll number:”<<rollnumber<<”\n”; } Class test: public student { Protected: Float sub1; Float sub2; Public: Void getmarks(float,float); Void putmarks(void); }; Void test::getmarks(float x, float y) { Sub1=x; Sub2=y; } Void test::putmarks() { Cout<<”marks in sub1=”<<sub1<<”\n”; Cout<<”marks in sub2=”<<sub2<<”\n”; } Class result : public test {

• • • • • • • • • • • • • • • • • • •

Float total; Public: Void display(void); }; Void result::display(void) { Total=sub1+sub2; Putnumber(); Putmarks(); Cout<<”total=”<<total<<”\n”; } Int main() { Result student1; Student1.getnumber (111); Student1.getmarks(70.0,58.5); Student1.display(); Return 0; }

• • • • • • • • • • • • • • • • • • • •

MULTIPLE INHERITANCE #include<iostream.h> #include<conio.h> class add { protected: int val; public: void sum(int a,int b) { val=a+b; } }; class sub { protected: int res; public: void minus(int a,int b) {

• • • • • • • • • • • • • • • • • •

res=a-b; } }; class mul:public add,public sub { private: int prod; public: void display() { cout<<"\n OUTPUT"; cout<<"\n~~~~~~~~"; cout<<"\n\n Added Value = "<<val; cout<<"\n\n Subtracted Value = "<<res; prod=val*res; cout<<"\n\n Product = "<<prod; } };

• • • • • • • • • • • •

void main() { clrscr(); int x,y; mul s; cout<<"\n Enter 2 numbers : \n"; cin>>x>>y; s.sum(x,y); s.minus(x,y); s.display(); getch(); }

Derived-constructor • The derived class need not have a constructor function as long as no base class constructor takes any arguments. If any base class contains a constructor with one or more arguments,then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors. The general form is, • • • • • • • • Derived-constructor (arg1,arg2,..... arg n, arg D) base1(arg1), base2(arg2), ….... basen(arg n), { body of derived constructor using arg D }

Polymorphism • The two types of polymorphism are, • • Compile time polymorphism – The compiler selects the appropriate function for a particular call at the compile time itself. It can be achieved by function overloading and operator overloading. • • Run time Polymorphism - The compiler selects the appropriate function for a particular call at the run time only. It can be achieved using virtual functions • Program to implement runtime polymorphism: • include<iostream.h> • #include<conio.h> • template<class T> • T sqr(T & n) • { • return(n*n); • }

• • • • • • • • • • • • • • • • •

void main() { int a; float b; double c; clrscr(); cout<<"\n\n Enter an Integer : "; cin>>a; cout<<"\n Square of a = "<<sqr(a)<<endl; cout<<"\n\n Enter a Float Value : "; cin>>b; cout<<"\n Square of b = "<<sqr(b)<<endl; cout<<"\n\n Enter a Double Value : "; cin>>c; cout<<"\n Square of c = "<<sqr(c); getch(); }

TYPE CONVERSION
There are three types of conversions. They are • Conversion from basic type to class type – done using constructor • Conversion from class type to basic type – done using a casting operator • Conversion from one class type to another – done using constructor or casting operator //TYPE CONVERSION FROM ONE OBJECT TO ANOTHER OBJECT • #include<iostream.h> • #include<conio.h> • class sample • { • private: • int val; • public: • sample(int a,int b,int c) • { • if((a>b)&&(a>c)) • val=a; • else if(b>c) • val=b;

• • • • • • • • • • • • • • • • • • •

else val=c; } int send() { return val; } }; class sample1 { private: int y; public: sample1() { } sample1(sample s1) { y=s1.send();

• • • • • • • • • • • • • • • • • •

} void print() { cout<<"\n Greatest number is : "<<y; } }; void main() { int a,b,c; clrscr(); cout<<"\n Enter three numbers \n"; cin>>a>>b>>c; sample s1(a,b,c); sample1 s2; s2=s1; s2.print(); getch(); }