oops. oops concepts classes objects data abstraction and encapsulation inheritance polymorphism...

62
OOPS

Upload: arleen-andrews

Post on 26-Dec-2015

248 views

Category:

Documents


1 download

TRANSCRIPT

OOPS

OOPS Concepts

• Classes• Objects• Data Abstraction and Encapsulation• Inheritance• Polymorphism• Dynamic Binding• Message Passing

CLASSESA class is a user defined data type which holds both the data

and functions.

The Internal data of a class is called member data and the functions are called member functions.

The variable of a class are called objects or instances of a class.

The class construct provides support for data hiding, abstraction, encapsulation, single inheritance, multiple inheritance, polymorphism and public interface functions for passing message between objects.

Syntaxclass user_defined_name

{

private:

data_type members

implementation operations

public:data_type membersimplementation operations

protected:data_type membersimplementation operations

};

OBJECTSIt is basic run – time entity

ExampleObjects are accessed, created or deleted during program run-time.

The tool bar at the top of your browser is an example of  an 'object'. Want to print this page?

Click the print button. Need to read the page you were on before this? Click the back button.

Objects are what you are used to using  when you use a program with as graphical user interface (GUI). You should never have to 'look inside' the box.

Objects 'interact' with the user, but they can also interact with each other and they can be put together in groups, collections, arrays or lists. 

Defining the object of a Classclass user_defined_name

{

private:

//data

//methods

public:

//methods

protected:

//data

};

user_defined_name object_1,object_2,object_3……object_n;

Defining the object of a Classclass student

{

private:

int rollno;

int age;

public:

void getinfo();

void disinfo();

}obj1,obj2,obj3;

Accessing a Member of ClassSyntax:

class_object.data_member;

class_object.function_member;

Ex:

obj1.rollno = 2345;

obj1.getinfo();

Data Encapsulation

• The technical term for combining data and functions together as a bundle is encapsulation.

#include <iostream.h>

class Adder

{ public:

// constructor Adder(int i = 0) {

total = i; }

// interface to outside world

void addNum(int number)

{

total += number;

}

// interface to outside world

int getTotal()

{

return total;

};

// hidden data from outside world

private: int total;

};

int main( )

{

Adder a;

a.addNum(10);

a.addNum(20);

a.addNum(30);

cout << "Total " << a.getTotal() <<endl;

return 0;

}

Function Oriented Programming

Object Oriented Programming (OOP)

User defined types Classes

Variables Objects

Structure members Instance variables

Functions Methods

Function call Message passing

Difference Between Function Oriented and Object Oriented

DATA HIDINGThis concept is the main heart of an Object oriented programming.

The data is hidden inside the class by declaring it as private inside the class.

When data or functions are defined as private it can be accessed only by the class in which it is defined. When data or functions are defined as public then it can be accessed anywhere outside the class.

Object Oriented programming gives importance to protecting data which in any system. This is done by declaring data as private and making it accessible only to the class in which it is defined.

This concept is called data hiding. But one can keep member functions as public.

The Protecting the data in OOPS in three types

1. Private

2. Protected

3. Public

PrivateA member data can only be accessed by the member function

and friends of this class. The member functions and friends of this class can always read or write private data members. The private data member is not accessible to the outside world.

ProtectedThe members which are declared in the protected section, can

only be accessed by the member functions and friends of this class. Also, these functions can be accessed by the member functions and friends derived form this class. It is not accessible to the outside world.

PublicThe members which are declared in the public section, can be

accessed by any function in the outside world (out of the class). The public implementation operations are also called as member functions or methods, or interfaces to out of the class.

Example

class date{

private:int day;int month;int year;

};

class student{

private:int rollno;int age;char sex;float height;float weight;

publicvoid getinfo();void disinfo();

};

Member Data

Member Function

Example

class date{

int x;int y;

};

class date{

private:int x;int y;

};

By default members are private

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

{public:

int day;int month;int year;

};void main(){

clrscr();

class date today;today.day = 10;today.month = 3;today.year = 1995;cout<<"Today's date is = "<<today.day <<"/";cout<<today.month<<"/"<<today.year<<endl;

getch();}

#include<iostream.h>#include<conio.h>class date{

private: // by default, members are privateint day;int month;int year;

public: // Privatevoid getdata(int d,int m,int y){

day = d;month = m;year = y;

}void display(void){

cout<<"Today's Date is = "<<day<<"/";cout<<month<<"/"<<year<<endl;

}};void main(void){

clrscr();class date today;int d1,m1,y1;d1 = 10;m1 = 12;y1 = 1994;today.getdata(d1,m1,y1);today.display();getch(); }

#include<iostream.h>#include<conio.h>class sample{ private:

int x;int y;

public:void getinfo(){

cout<<"enter any two numbers ?"<<endl; cin>>x>>y;}void display(){ cout<<"X = "<<x<<endl; cout<<"Y = "<<y<<endl; cout<<"Sum = "<<sum()<<endl; cout<<"Diff = "<<diff()<<endl; cout<<"Mul = "<<mul()<<endl; cout<<"Div = "<<div()<<endl;}int sum(){

return(x+y);}

int diff(){

return(x-y);}int mul(){

return(x*y);}int div(){

return(x/y);}};void main(void){

clrscr();

sample obj1;

obj1.getinfo();obj1.display();

getch();}

INHERITANCE

What is Inheritance?

Inheritance is the mechanism which allows a class B to inherit properties/characteristics-

attributes and methods of a class A. We say “B inherits from A".

A

B

Super Class or Base Class or Parent Class

Sub Class or Derived Class or Child Class

What are the Advantages of Inheritance

1. Reusability of the code.

2. To Increase the reliability of the code.

3. To add some enhancements to the base class.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class.

This existing class is called the base class, and the new class is referred to as the derived class.

Inheritance achieved in two different forms

1. Classical form of Inheritance

2. Containment form of Inheritance

Classical form of Inheritance

We can now create objects of classes A and B independently.

Example:

A a; //a is object of A

B b; //b is object of B

A

B

Super Class or Base Class or Parent Class

Sub Class or Derived Class or Child Class

• Base & Derived Classes:

• A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:

• class derived-class: access-specifier base-class

Access Control and Inheritance

• We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied:

• Public Inheritance: When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

• Protected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.

• Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.

In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as ‘is – a’ relationship

Example

1. Dog is – a type of animal

2. Manager is – a type of employee

3. Ford is – a type of car

Animal

Horse LionDog

Types of Inheritance

1. Single Inheritance (Only one base Class)

2. Multilevel Inheritance (Derived from a Derived Class)

3. Multiple Inheritance (Several Base Classes)

4. Hierarchical Inheritance (One Base Class, Many Subclasses

5. Hybrid Inheritance (combination of Multilevel and Multiple (or) combination of

Multiple and Hierarchical)

1. Single Inheritance (Only one Base Class)

A

B

2. Multilevel Inheritance (Derived from a Derived Class)

A

B

C

3. Multiple Inheritance (Several Base Classes)

A B

D

C

4. Hierarchical Inheritance (One Base class, Many Subclasses)

5. Hybrid Inheritance

A

B

D

C (OR)

A

D

CB

A

B DC

1. Single Inheritance (Only one Base Class)

Single Inheritance is the process of creating new classes from an existing base class. The existing class is known as the direct base class and the newly created class is called as a singly derived class.

Single Inheritance is the ability of a derived class to inherit the member function and variables of the existing base class.

Defining the derived class

1. The keyword class

2. The name of the derived class

3. A single colon

4. The type of derivation (private, public or protected)

5. The name of the base or parent class

6. The remainder of the class definition

Syntax:

class derived_class_name : private / public / protected base_class_name

{

private:

//data members

public:

//data members

//methods

protected:

//data members

};

Some Important characteristics of inheritance are:

1. A derived class extends its direct base class. It can add new members to those if inherits, however, it cannot change or remove the definition of an inherited member.

2. Constructors and Destructors are inherited. All other members, regardless of their declared accessibility in base class, are inherited. However, their accessibility in the derived class depends on their declared accessibility in the base class.

3. A derived class can override an inherited member.

class A{

private:int x;

public:void getd_1();void putd_1();

};

class B:public A{

private:int y;

public:void getd_2();void putd_2();

};

void A::getd_1(){

cout<<"Enter the X Value"<<endl;cin>>x;

}void A::putd_1(){

cout<<"The X Value is:"<<x<<endl;}

void B::getd_2(){

cout<<"Enter the Y Value"<<endl;cin>>y;

}void B::putd_2(){

cout<<"The Y Value is:"<<y<<endl;}

void main(){

clrscr();

B b;

b.getd_1();b.putd_1();

b.getd_2();b.putd_2();

getch();}

Base – Class Access Control

class A{

protected:int x;

};

class B:public A{

private:int y;

public:void getd_1();void putd_1();

};

void B::getd_1(){

cout<<"Enter the X Value"<<endl;cin>>x>>y;

}void B::putd_1(){

cout<<"The X Value is:"<<x<<endl;cout<<“The Y Value is:”<<y<<endl;

}

void main(){

clrscr();

B b;

b.getd_1();b.putd_1();

getch();}

Inheritance and Protected Members

TYPES OF DERIVATION

1. Public Inheritance 2. Protected Inheritance 3. Private Inheritance

Public Inheritance

1. Each public member in the base class is public in the derived class.

2. Each protected member in the base class is protected in the derived

class.

3. Each private member in the base class remains private in the base

class.

class baseA

{

private:

int x;

protected:

int y;

public:

int z;

};

class derivedD : public baseA

{

private:

int w;

};

Member in DerivedD Access Status How Obtained

x Not accessible From class baseA

y protected From class BaseA

z public From class BaseA

w private Added by class derivedD

Protected Inheritance

1. Each public member in the base class is protected in the derived class.

2. Each protected member in the base class is protected in the derived

class.

3. Each private member in the base class remains private in the base

class.

class baseA

{

private:

int x;

protected:

int y;

public:

int z;

};

class derivedD : protected baseA

{

private:

int w;

};

Member in DerivedD Access Status How Obtained

x Not accessible From class baseA

y protected From class BaseA

z protected From class BaseA

w private Added by class derivedD

Private Inheritance

1. Each public member in the base class is private in the derived class.

2. Each protected member in the base class is private in the derived

class.

3. Each private member in the base class remains private in the base

class.

class baseA

{

private:

int x;

protected:

int y;

public:

int z;

};

class derivedD : private baseA

{

private:

int w;

};

Member in DerivedD Access Status How Obtained

x Not accessible From class baseA

y private From class BaseA

z private From class BaseA

w private Added by class derivedD

class baseA{

private:int i;

public:void getdata(int x);void display();

};class baseB{

protected:int j;

public:getdata(int y);void display();

};

class derivedC:public baseA, public baseB{};

void baseA :: getdata(int x){

i = x;}void baseA :: display(){

cout<<"Value of i = "<<i<<endl;}

void baseB :: display(){

cout<<"Value of J = "<<j<<endl;}

Ambiguity in Single Inheritance

void main(){

clrscr();

derivedC objc;

int x,y;

cout<<"Enter the value i"<<endl;cin>>x;cout<<"Enter the value j"<<endl;cin>>y;

//objc.getdata(x);//objc.getdata(y);//objc.display();//objc.display();

objc.baseA :: getdata(x);objc.baseB :: getdata(y);objc.baseA :: display();objc.baseB :: display();

getch();}

Ambiguity

POLYMORPHISMDefinition:

Polymorphism means to have one interface for different methods or functions. It is the ability through which we can do different operations (by calling different functions) from the same interface.

Types of Polymorphism:

Polymorphism

Compile Time Polymorphism

Run Time Polymorphism

Function Overloading

OperatorOverloading

VirtualFunction

Run – Time Polymorphism

Run-Time Polymorphism: When the call to a particular function (out of the many polymorphic functions) is not resolved (or known) until execution then it is called run-time polymorphism.

Virtual Functions

Example of run time polymorphism:

class Base { public: virtual void show() { cout << "Base class"; } };

class Derived:public Base

{

public: void show()

{

cout << "Derived Class";

}

};

int main()

{

Base* b; //Base class pointer

Derived d;

//Derived class object b = &d;

b->show(); //Late Binding Ocuurs

}

Output

Derived Class

Pure Virtual Function & Abstract Classes

A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same.

#include<iostream.h> 

class Base

{

   int x;

public:

    virtual void fun() = 0;

    int getX()

{

return x;

}

};

 

// This class inherits from Base and implements fun()class Derived: public Base{    int y;public:    void fun() { cout << "fun() called"; }}; int main(void){    Derived d;    d.fun();    return 0;}Outputfun() called

Abstract ClassesA class is abstract if it has at least one pure virtual function.

In the following example,

Test is an abstract class because it has a pure virtual function show().

/ pure virtual functions make a class abstract

#include<iostream.h> 

class Test

{

   int x;

public:

    virtual void show() = 0;

    int getX() { return x; }

};

int main(void)

{

    Test t;

    return 0;

}

Output

Compiler Error: cannot declare variable 't' to be of abstract type 'Test' because the following virtual functions are pure within 'Test': note: virtual void Test::show()

Compile – Time Polymorphism

Compile-Time Polymorphism: When we have two or more polymorphic function (overloaded functions) and the call to a particular function is resolved (or known) at the compile-time, it is called compile-time polymorphism.

#include <iostream.h>

class Value{protected:int val;public:void set_values (int a){

val=a;

}};

class Cube: public Value

{public:int cube(){

return (val*val*val); }};

int main ()

{Cube cb;Value * ptr = &cb;ptr->set_values (10);cout << "The cube of 10 is::" << cb.cube() << endl;return 0;

}

Output

The cube of 10 is:: 1000

FUNCTION OVERLOADING

Function overloading is a logical method of calling several functions with different arguments and data types that perform basically identical things by the same name.

The main advantages of using function overloading are:

1. Eliminating the use of different function names for the same operation.

2. Helps to understand, debug and grasp easily.

3. Easy maintainability of the code.

4. Better understanding of the relation between the program and the outside world.

Types of Function Overloading

1. Function Overloading with Various Data Type

2. Function Overloading with No. of Arguments

1. Function Overloading with Various Data Type

#include <iostream.h>

void main ()

{

void swap (int,int);

void swap (float,float);

void swap (char,char);

swap (a1,b1);

swap (a2,b2);

swap (a3,b3);

}

Functions are declared

Function are called with same name

1. Function Overloading with No. of Arguments

#include <iostream.h>

void main ()

{

void swap (int);

void swap (int,int);

void swap (int,int,int);

swap (a1);

swap (a1,b1);

swap (a1,b1,c1);

}

Functions are declared

Function are called with same name

Special Features of Function Overloading

Case 1:

The function arguments must be sufficiently different since the compiler cannot distinguish which function to be called when and where.

#include <iostream.h>

void main()

{

int funct1 (int);

int funct1(int &a);

funct(x);

}

int funct(int)

{

}

Int funct1(int &a)

{

}

Error, Both the arguments are same int and int &

Special Features of Function Overloading

Case 2:

While typedef is used for declaring a user defined name for functions and variable, it is not a separate type but only a synonym for another type.

#include <iostream.h>

void main()

{

typedef float real;

void funct1 (real);

int funct1(float);

funct1(x);

}

int funct(real) // Error

{

}

Int funct1(float)

{

}

Error, Function arguments are same

Special Features of Function Overloading

Case 3:

Even though the values of enumerated data types are integers, they are distinguished from the standard data type of int. So whenever a function is declared with function argument of int and an enumerated data type, it is valid in C++ for function overloading

#include <iostream.h>

void main()

{

enum day{mon,tue,we};

void funct1(int i);

void funct1(day);

}

int funct(int)

{

}

Int funct1(day)

{

}

Valid, even the value of day is integer quantity

Special Features of Function Overloading

Case 4:

The pointer arguments of a pointer variable and an array type are identical.

#include <iostream.h>

void main()

{

int funct1 (char *,char *);

int funct1(char [], char []);

funct(a,b);

}

int funct(char *a,char *b)

{

}

Int funct1(char a[],char b[])

{

}

Error, The compiler will display the error message as ‘redeclaration of the function funct1()’.

OPERATOR OVERLOADING

The C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meanings to an operator is known as operator overloading.

Operator Overloading provides a flexible option for the creation of new definitions for most of the C++ operators. We can almost create a new language of our own by the creative use of the function and operator overloading techniques.

Defining Operator OverloadingTo define an additional task to an operator, we must specify what it means in

relation to the class to which the operator is applied.

This is done with the help of a special function, called operator function, which describes the task.

The general form of an operator function is:

return_type class_name :: operator op (arg_list) return_type operator op(arg_list)

{ {

Function_Body Function_Body)

} }

retrun_type -> The type of value returned by the specified operation.

op -> The operator being overloaded.

operator -> The op is preceded by the keyword operator.

operator op is the function name

Defining Operator Overloading……. Difference between Friend and Non – Static member in Operator Overloading

1. Operator functions must be either member functions (non – static) or friend functions.

2. A Friend function will have only one argument for unary operators and two for binary operators.

3. In a Non – Static member function has no arguments for unary operators and only one for binary operators. This because the object used to invoke the member function is passed implicitly and therefore is available for the member function.

4. Arguments may be passed either by call by value or call by reference in both member function and friend function.

5. Operator functions are declared in the class using prototypes as follows:

void operator + (void);

vector operator – ( );

friend vector operator + (vector_1, vector_2);

friend vector operator – (vector);

friend int operator == (vector_1,vector_2)l

Vector is a data type of class and may represent both magnitude and direction or a series of points called elements.

The process of overloading involves the following steps:

1. Create a class that defines the data type that is to be used in the overloading operation.

2. Declare the operator function operator op () in the public part of the class. It may be either a member function or a friend function.

3. Define the operator function to implement the required operations.

Overloaded operator function can be invoked by expressions such as

op x or x op

for unary operators and

x op y

for binary operators op x (or x op) would be interpreted as

operator op (x)

for friend functions. Similarly, the expression x op y would be interpreted as either

x.operator op (y)

In case of member function, or

operator op (x,y)

Rules for Overloading Operators

1. Only existing operators can be overloaded. New operators cannot be created.

2. The overloaded operator must have at least one operand 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. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.

5. There are some operators that cannot be overloaded.

6. We cannot use friend function to overload certain operators. However, member functions can be used to overload them.

7. Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument.

8. Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments.

Rules for Overloading Operators. . . . . . . .

9. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class.

10. Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments.

sizeof Size of Operator

. Membership Operator

.* Pointer – to – member Operator

:: Scope Resolution Operator

?: Conditional Operator

Operators that cannot be overloaded

Where a friend cannot be used

= Assignment Operator

( ) Function call Operator

[ ] Subscripting Operator

-> Class member access Operator

if(typeid(i) == typeid(j))cout << "The types of i and j are the same\n";if(typeid(i) != typeid(f))cout << "The types of i and f are not the same\n"; if(typeid(ob1) !=

typeid(ob2))cout << "ob1 and ob2 are of differing types\n";return 0;}

OUTPUT

The type of i is: intThe type of f is: floatThe type of p is: char *The type of ob1 is: class myclass1The type of ob2 is: class myclass2The types of i and j are the sameThe types of i and f are not the sameob1 and ob2 are of differing types