Vous êtes sur la page 1sur 20

Object Oriented Programming

Programming Languages (Support Object Oriented Concepts)


Smalltalk
Simula
ADA 1968-70
Objective C
C++
Pure Object Oriented Programming Languages
Java
C#
Compiler for C++
Borland c++
Visual C++
Turbo C++

Improvement in C++ with compared to C:-


 In C function protype is not essential before function calling, while c++ programs struck checking by fun C
calling so in c++ either function protype or function body must be define before function calling. It not then
compiler gives error.
 Both C&C++ has default return type integer, if we do not specify function return type. But c++ compiler warns
the user if function does not any value and its return type is not void.
 C compiler has a work. If we skip the no. of arguments specified in function definition, c compiler assumes
garbage value for the argument specked by the user.

C++ compiler gives error in such a situation for Example:


# include <stdio.h>
Void f1 ( int a, int b, int c)
{
printf (“\n %d \t %d”, a, b, c);
}
void main ( )
{
f1 (10, 50, 30);
f1 (10, 50);
f1 (10);
f1 ( );
}

Comment style
 Multi line comment (/* Comment *)
 Single line comment (// Comment)

New style of type coasting


 (int) a // c style also supported by c++
 int (a) // c++ style

input,output
 include<stdio.h> // in C Language
 include<iostream.h> // in C++ Language
In C Language In C++ Language
printf(“\n welcome to c”); cout <<”\ n welcome to c”;
printf (“%d%f%s”, a, b, c); cout << a<<b <<c;
printf (“\n value is %d and %d”, a, b); cout<<”\n value is” <<a<<”and”<<b<<endl; cin >> a;
scanf (“%d”, &a); cin >>a>>b>>c;
scanf(“%d%f%c”, &a, &b, &c”, &a, &b, &c); cin >>str;
scanf (“%s”, str); cin.getline(str, 20);
gets(str); cout<<int(‘A’);
printf(“\n %d”, ‘A’);

Inline function

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
 Inline function is the new-featured introduced in c++ Information Technology is a request to c++ compiler to
write a function body instead of function address, whenever function has called.
 Inline function is a request not a instruction, compiler is not bound to make function inline, compiler take
decision on the basis of size of function if Information Technology is small compiler make it is small compiler make
it inline else now.
 By making a function inline we can improve the execution speed of the program.
 To make a function inline we use keyword inline in front of function prototype or function body whichever
comes first in program.
 In earlier versions of c++ compiler we do not have any way to assure that function is inline or not, but in new
version we have keyword out line for checking this.
 All the member function of class are inline by default.

Syntax –
inline int f1 ( )
{
-----
-----
}

1. In c language all the declaration must be before any executable statement, but in c++ variable be declared any
where inside the program before its use.
2. C++ is developed as superset of c language, so c++ compiler support or can compile all c programs. If we want
to instruct c++ compiler that program should be compiled as c compiler not as c++ compiler. We have two methods

(i) Save the file with extension .c
(ii) extern “c”
{
-------
------- Only that part compiled by c compiler
-------
}
3. Difference in dynamic memory allocation - In c for DMA for use library function, but in c++ for DMA we
have new & delete keyword, which is better than c approach.

In C Language In C++ Language


int * pa ; int * pa;
Pa = (int ) malloc (size of (int)10); pa = new int [10];
……. …….
delete pa;

free (pa);
Default Argument - c++ introduces a default arguments default arguments are the default values of defined formal
parameters which is used by the compiler if we skip actual parameter for formal parameters by passing values, default
arguments will not be used.
Default argument is specified with prototype of function or with function body which ever comes first. If we are using
default argument value for an argument we have to use default value for all the arguments, which come right to that
argument.
Ex.
float si (float p, int t=5, float r=10)
{
return ( p * r * t / 100);
}
main ()
{
cout << si (5000, 10, 20);
cout << si(5000, 10); // rate = 10 by def.
cout << si (5000); // rate = 10, time = 5
cout << si (); // error
cout << si (5000, 30); // error

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
In right all value are taken as default arguments.

Function overloading – Function overloading is a very important feature of OOP. By function overloading we
implement design time polymorphism in program. C++ gives us capability to write more than one function with same
name but different signature, such type of functions are called overloaded function and this feature is known as function
overloading.
For Function Overloading –
- Name of the function must be same.
- Their argument list must be different.
- The return type of function does not matter while function overloading.
- Function overloading give us capability to use most appropriate name for more than are function.
- To overload function argument list must be different an arguments data types, their sequence or number of
arguments passed. This difference is essential to identify the function which should be called.
Ex.
int f1 (int, int)
int f1 (int, float) int add (int a, int b)
int f1 (int m, int, int) { return a + b; }
int f1 (float, int ) float add (float a, float b)
float f1 (int, int) { return a + b; }
int f1 (float, float)

void f1 (int, int) void main ()


void f1(float, float) {
void f1 (int, float) float f1 = 10.5, f2 = 5.7;
void f1 (float, int) int x = 10, y = 20;
void f1 (int, int, int)
void f1(float, int float)
cout << add (f1, f2)<< endl;
void f1 (int, float, double) not overloading case cout << add (x, y) << endl;
float f1 (float, float) function not allow }

References - Reference variables are the name for pre-existing variables.


- Information Technology is not another copy of variable but just another name for existing variable.
- Information Technology does not occupied separate m/r space.
- Declaration & initialization of reference variable must be in single line.
- Data type of reference and the variable must be same.
- A variable can have any no. of references.
- Once a reference is assign to a variable we can not remove or assigning to another variable.
- The use of reference is to simplify the call by reference but Information Technology is not the replacement of
pointer.
Ex.
void main()
{
int a = 10;
int &b = a;
int &c = a;
cout << a << b << c<<endl; //10 10 10
cout << &a << &b << &c << endl;
a++;
cout<<a<<b<<c<<endl; //11, 11, 11
}

void f1(int x, int y) // x[10] y[12]


{
x ++; //11
y++; //13
cout <<x<<y<<endl; //11, 13
}

void f2 (int *px, int *py)


{
*px = *px + 1;
*py = *py + 1;

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
cout <<*px<<*py<<endl; //11, 13
}

void f3(int &s, int &n) {


s++; //12
n++; //14
cout << s<<n<<endl;
}

void main () {
int a = 10, b = 12; // a[10] b[12]
f1(a, b); //11, 13
cout<<a<<b<<endl; //10, 12
f2(&a,&b) //11, 13
cout <<a<<b<<endl; //11, 13
f3(a, b); //12, 14
cout <<a<<b<<endl; //12, 14
}
Object - Object is an entity can be identified uniquely because of its feature. A object is defined by its features, which
are properties, method and state.
Class – “Class is a logical representation of object” it is collection of properties and method but don’t have state, these
properties and method is implemented when we create a instance of class called object.

OOP Features –
1. Class and object
2. Abstraction
3. Encapsulation
4. Inheritance
5. Aggregation
6. Message Passing
7. Meta classes
8. Links and Association
9. Grouping of class
10. Polymorphism
11. Dynamic Binding

Abstraction
Abstraction is the major feature of the OOP’s language abstraction means abstracting the meaningful and hide non-
meaningful / less meaningful.
There are two types of abstraction –
(i) Data Abstraction - Using a data type without knowing its implementation details in its m/r
representation is called data abstraction. C provide data abstraction for primitive data type but not for user
defined data types. In c++ and OOP we get data abstraction for primitive and user defined both data type.
(ii) Procedural Abstraction -A function or procedure can be used without knowing its body. Only the
prototype of the function we should know to call the function, so hiding procedural implementation details
is procedural abstraction.

Encapsulation -Encapsulation means putting data and methods, working on that data together sis called encapsulation.
By this way we can simplify the modification in programming and the nature of data can be stored in comparatively
easier way. The structured approach is called “ procedure centric” and object-oriented approach is called “data centric”.
Polymorphism - Polymorphism is again to simplify OOP. Polymorphism is a characteristic in which different entity,
performing different tasks, is appears in most generalized way or common methods.
Polymorphism is common feature of OOP languages and in c++ there are two types of polymorphism.
(i) Design time polymorphism - Achieved by function overloading and operator over loading.
(ii) Run time polymorphism - Achieved by virtual function and abstract classes.
Inheritance – Inheritance is known as most powerful feature of the class and objects. Information Technology is a way
to established relationship between classes.
There are two types of relationships –
(i) is king of
(ii) is part of
Inheritance is a way to establish “is kind of” relationship between classes. In inheritance class inherited from others is
known as “parent class”. All the features of parent class come into child class through inheritance.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
There are so many types of inheritance like simple inheritance, multilevel inheritance, hierarchical inheritance, multiple
inheritances, and hybrid inheritance.
Inheritance is used for two main purposes –
(i) Reusability with extendibility
(ii) Generalization and specialization

parent Vehicle

child Four Two


wheeler wheeler

Generalization Bus Car Bike Scooter

Specialization

Allegation - Information Technology is used to “ is part of” relationship between classes. Information Technology is
also known as container components relationship, part-own relationship. In aggregation container object aggregate or
group the components objects. We can say that container consist of component. Here container delegates the task to the
components.

House

Door Window
Message Passing - Communication between two objects is known as message passing. It is performed by calling
methods of objects.

F1 ( )
Objec Objec
t1 t2

F2 ( )

Syntax - Object.method ( )

Meta Classes – Meta class is a class of class. Meta class contains features of class as class contains features of object.
The features implemented in meta class are true members of class, which door not belongs to individual object but class.
In c++ we use “static members” to represent meta class.
Links and Association - A link is a physical or conceptual connection between object instance. A link is an instance of
an association. An association describes a group of links with common structure and common summative.
Ex. Student enrolled in course.
This an association while in this case
Manish enrolled in M.C.A. this is link. void main ()
(i) Grouping of Classes – In c++ {we use “name spaces” and in java we use “packages” for
grouping of class, so naming conflicts willlength
be resolved.
L1, L2, L3;
(ii) Dynamic Binding –
L1.setdata (10, 50);
L2.setdata (20, 30);
L3.setdata (30, 40);
K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3
L1.showdata ( );
2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
L2.showdata ( );
L3.showdata ( );
}
#include <iostream.h>
class length {
Private:
int m, cm;
public:
void setdata (int a, int b)
{
m = a; cm = b;
}
void showdata ( )
{
cout << “m is”<<m<<endl;
cout <<”cm is”<<cm<<endl;
}
};
void main ( )
{
length L;
L.setdata(10, 50);
L.showdata( ) ;
}

In c++ class is used to define a user defined data type.


Syntax :-

class <class name> /* declare class */


{
------
[Data Member & Member Functions]
------
};
Class_name object_ name; /* Declare object*/
object_name.member /* Access member from object */

(i) A class is a collection of variables and functions, these are known as data member and member function of
the class.
(ii) A class does not exactly gets m/r, but the object of the class is the real m/r representation of the class. The
m/r allocated to the object of the class is always depends on size of data members in class, each object of class get
separate m/r for data members and only one copy of member function will be created in m/r that is shared by all the
object of class.
Ex.
Length a, b, c; a b c
m cn m cn m cn

Set data ( ) show data ( )


Ex.
class test
{ };
void main ( )
{
cout << size of (test) << endl;
}
output is : 1
If a class does not have any data member even than that class object will get one byte in memory, which is to assure
unique memory address for objects.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
This one byte cannot be used to store data.

(iii) All members of class comes in a access specifier Private, protected or Public. If access specifier is not
specified default access specifier is “Private” for class. Private member of the class are accessible only by the
member of class. Information Technology can’t be access outside the class, while Public member can be accessed
any where inside the program. Because all members are object member they must be called with object.

Private:
F2 ( )
Int b Not access

public:
F1 ( )
Int a Object name access
(iv) In c++ structured and class both are same. Structured can also contain functions and all other object
oriented programming features. The only difference between these two is the by default, member of class are Private
and member of structure are Public.
(v) In c++ scope of variables is of three types :
- global
- instance
- local

int a; // global variable };


class test{ void length:: setdata (int m, int cm) {
int b; // instance variable length ::m = m;
void f1 ( ) length :: cm = cm;
{ valid( );
int c; // local variable }
cout <<a<<b<<c void length : : showdata( )
{
int a; cout << “m is” <<m <<endl;
class test cout << “cmis” <<cm<<endl;
{ }
int a; void length :: valid ( )
void f1( ) {
{ if (cm < 0) cm = 0
int a; if (m < 0) m = 0;
cout <<a; //local if (cm >= 100) {
cout<<::a; //global m + = cm / 100;
cout<<test::a; //instance cm % = 100; }
};
class length { void main ( )
Private: {
int m, cm; length x;
void valid ( ); x.setdata (100, 576);
public: x.showdata ( );
void setdata (int, int); }
void showdata ( );

Constructor
1) Constructors are the special methods having same name as class name and call automatically when instance of
the class is created.
2) The purpose of constructor is to define initial state of the object.
3) The calling of constructor is implicit and at the time of object declaration. They can’t be called explicitly. So
calling of constructor is only once in the life of an object.
4) Constructor does not have any return type. Even ‘void’ can’t be defined as the ‘return’ type of constructor.
5) Constructor can be overloaded.
6) By default c++ provide a no argument constructor for each class. This constructor can be override whenever
required.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
7) If constructor with argument is defined for a class we have to override no argument constructor {available by
default}.
8) Constructors can be Private, Public.
9) Constructors can not be virtual, friend functions.

Destructor
1) Destructors are the special methods, which called automatically, when object of the class is being destroyed.
2) The m name of destructor is same as class name preceded by ‘~’ symbol.
3) Only are destructor can be defined for a class, destructor does not have any return type or arguments.
4) c++ does not provide any default destructor for a class.
5) Purpose of destructor is not to destroy the object but to free them resources linked dynamically with that object.
6) The calling of destructor is in LIFO order, means the object which is created first will be destroyed at last.
7) Destructor must be in Public section.
8) Destructor cannot be virtual and friend function.

Friend Functions
1) It is the non member functions of a class, which can access any member of class, Private, Public or protected.
2) To make a function friend to a class, its signature should be declared as a friend in class. This declaration can be
in Private, Public or protected section.
3) Friend functions is unique feature of c++ which violates the rules of OOP, so its used should be minimize as
possible.

Friend Classes
1) Suppose class A is declared friend to class B then any member of class A can access any member of class B. but
vice-versa is not true.
2) Similar to friend function, friend, classes violates the rules of OOP. So there used should be minimize as
possible.

Static members of the class


In a class there are two types of members.
1) Static and
2) Non static
The Non-static members are the true members of the object, which does not belong to class. While static member is the
true member of the class.
Static members are the way to represent meta class members. A meta class is class of class.

Static Data Member - Class data members declared static gets only one copy in m/r before instantiation of class only
one copy of static member is created that can be accessed by any object or directly by class name. Static data members
must be declared twice once within class and once outside class. If not initialized there default initial value us zero.

String void main () {


cout << test ::b << endl; // 10
class string { test obj1, obj2;
char *str; obj1.a = 10;
public: obj1.b = 20;
string () obj2.a = 30;
{str = NULL; } obj2.b =40;
string (char *p) cout <<obj1.a<<obj1.b; //10, 40
{str = p; } cout << obj1.a<<obj2.b; //30, 40
string (string &a) }
{str = a.str; }
Static Member Functions
Static Data Member
class test {
class test private:
{ int a;
public : test () {
int a; cout << “constructor called”,
static int b; a = 0; }
}; public :
int test :: b = 10; void show () {
cout <<a<<endl;

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
}
void main() {
static test * getobject () { test *obj;
return new test; obj = test :: get object();
/*dynamically new object is created, obj->show();
this time constructor is called */ } delete obj; }
};

Aggregation
 There are two possibilities to established relationship between classes.
 Is kind of relationship and
 Is part of relationship

 Aggregation or container component relationship or part whole or has a relationship is the other name of “is
park of relationship” between classes.
 In this relationship existence of container object is based on its component object or we can say by grouping
of component container object is formed.
For example – computer is object, which consists of Hard disk, Processor, RAM, Keyboard etc.
In c++ there are two ways to implements this relationship.
Nested Class -A class declared inside another class is known as nested class or inner class and the class which contains It
is known as outer class. To access features of component we have to used container class.

class A { Declaring object of a class as a data member in other


class B class
{
public : class B {
void f1 () public :
{ cout <<”f1 of B”<<endl; } void f1()
}; { cout <<”f1 of B” << endl; }
public: };
B obj;
void f1() class A {
{cout <<”f1 of A” << endl; } public:
}; B obj;
void f1()
void main () { { cout ,, “f1 of A” << endl; }
A obj; };
Obj.f1();
Obj.obj.f1(); } void main () {
A obj;
Obj.f1();
Obj.obj.f1(); }

Anonymous class -A class without name is anonymous class. Because class don’t have any name.
1. We have to declared object of the class with class declaration.
2. Member of the class can’t defined outside the class.
3. Class can not contain static member
4. Explicit constructor can not be defined.
5. Can not be declared friend to other class.

class A {
public:
class {
public:
void f1()
{ cout <<”f1 of B” <<endl; }
} obj;
void f1() { cout <<”f1 of A” << endl; }
};
void main () {
A obj;
obj.f1();

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
obj.obj.f1(); }

Operator Overloading
1. It is the feature to implement design time polymorphism.
2. It is the capability of c++ programming language in which we can define the
behaviour of existing operators for user define data type.
3. Only existing overloaded we can not create out new operators.
4. Operators can be overloaded only for user defined data types. Behaviour of
operator for primitive data type can not be changed.
5. We can not changed precedence or associatively.
6. Operator overloading function must be member function of the class.
7. Following operators can not be overloaded-
(i) Conditional Operator (?)
(ii) Resolution Operator (:)
(iii) Member Access Operator (.)
(iv) sizeof Operator
(v) *
* By default only assignment operator can work with user define data types and only if objects are of same type, other
operator can’t work with user defined data type without operator overloading.

Operator overloading is not available in all object oriented, programming language. For ex. In java, VB, operator
overloading is not available.
This distinguished feature give power to c++ to simplify working with user defined data type and make user define data
type is similar to primitive data type in language.
length length::operator +=(length l){
class length { m + = l.m;
private: cm + = l.cm;
int m, cm; valid ();
void valid (); return *this; }
public:
length(); this pointer – this is a keyword in c++. The use of
length(int, int) this is possible only within non-static member
void setdata(int, int); function of a class.
void showdata(); this pointer is the pointer for object which call the
length operator +(length); function of
length operator += (length); this is the pointer to the current object.
length operator -(length); int length :: operator >(length temp) {
length operator -= (length): int a = m* 100 + cm;
int operator > (length); int b = temp.m*100 + temp.cm;
int operator < (length); return (a>b); }
int operator >= (length);
int operator <= (length); length length :: operator ++() {
int operator == (length); cm ++;
int operator != (length); valid ();
length operator ++( ); return*this; }
length operator ++(int);
length operator --( ); length length :: operator ++ (int a) {
length operator -- (int); length temp = *this;
length operator =(float); cm++;
}; valid ();
return temp; }
length length :: operator +(length l) {
length temp; length length :: operator = (float t) {
temp.m = m+l.m; m = t;
temp.cm = cm +l.cm; cm = ( t- m) * 100;
temp.valid(); return * this; }
return temp; }

Inheritance - It is known as most powerful features of oop after class and object itself. In inheritance we derive a new
class from a existing class in which features of existing class will come through inheritance.
We can add new features or modify the features which comes through inheritance.

Base Class
K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4

Derived Class
While inheritance when we define a new class we cannot change or modify features of base class although when these
features comes in derived class they can be modified. There are two measure benefits of inheritance –
1) Reusability with extendibility
2) Generalization & specialization
A class can also inherit properties from more than one class or from more than one level.

A derived class with only one base class is called single inheritance, and one with several base class is called multiple
inheritance. The traits of one class may be inherited by more than one class. This process is known as hierarchical
inheritance. The mechanism of deriving a class from another “derived class” is known as multilevel inheritance.

Type of Inheritance – There are so many types of inheritance.


 Single Level Inheritance (or Simple Inheritance)
 Multi Level Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance.
Single Level Inheritance Multi Level Inheritance Hierarchical Inheritance
or
Simple Inheritance A A

A
B
B C D
B Hybrid Inheritance
C

Multiple Inheritance A

A B C
B C

D
While programming there are only two types of inheritance
1) A class inherited from single class D
2) A class inherited from multiple class

Member of A class Accessible in


Private Right Wrong Wrong
Protected Right Right Wrong
public Right Right Right

class <derived class name>:<Access Specifier> <base class name>


{
---------
};

Base Class Access Specifier


Base class access specifier After inheritance new condition in derive class
Private Private Private Private
Protected Private Protected Protected
Public Private Protected Public

class A { private:

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
int x; {
protected: x, y, z, will be Private
int y; };
public:
int z; class B: protected A
}; {
x Private and will b y, z protected
class B: private A };

Base class access specifies the new access condition for the member of base class in derived class when they come
through inheritance.
If base class access specifier is not specified by default It is Private.
All the member of base class is inherited into derive class whether they are static or non static or whether they are
Private, Public or ported.
Friend function and friend classes are not inherited or we can say friendship is not inherited.
In derived class all the features of base class comes through inheritance we can add new features or modify existing
features which comes from base class by overriding them.

Example 1
class A { class B:A
private: {};
int a, b; void main () {
public: B obj;
int c; Cout << sizeof (obj) << endl; //6
}; }

Example 2 point :: x = x;
class A { point :: y = y; }
private:
int x, y; void show() {
public: cout << x << endl;
void set (int t1, int t2) cout << y << endl; }
{ x = t1; y = t2; } };
void show()
{ cout <<x<<y<<endl; } class point3D : public point {
}; private :
int z;
class B: public A
{ }; public : //automatically x = 0; y = 0;
point3D ()
int main () { { z = 0; }
B onb;
Obj.set(10, 20); point3D (int x, int y, int z) : point (x, y)
Obj.show (); { point 3D :: z = z; }
}
void set (int x, int y, int z) {
set(x, y);
class point point3D :: z = z; }
{
private : void show () {
int x, y; point :: show ();
cout <<z<<endl; }
public : };
point ()
{ x = 0; y = 0; } void main() {
point3D p;
point (int x, int y) { p.set(1,1,2);

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
p.set(1,2); }
p.show();
p.point::show ();

Constructor in case of Inheritance - By default derived class constructor call base class no argument constructor
before executing its body. But if we want that derived class constructor should call constructor of base class other than no
arguments we have to do It explicitly by following

Syntax:

drive class constructor (argument list ): Base class constructor (argument list)
{
---------
---------
---------
}

class A {
public: class C {
A () public:
{cout <<”in A” << endl; } void f1 ()
}; {cout << f1 of C”<<endl;}

class B: public A { void f3 ()


public: {cout <<”f3 of A “<<endl; }
B () };
{ cout <<”in B” << endl; }; class D : public A, public B, public C
{};
class c : public B {
public : void main () {
c() D obj ;
{ cout << “In c” << endl; } obj.A::f1();
}; obj.B::f1();
obj.C::f1();
void main ()
{ Obj.f1();
c obj; Obj.f2();
} }

Output F 2nd Method


In A
In B class D: A, B, C {
In C public:
void f1()
Multiple Inheritance { A::f1(); }
class A {
public : void f2()
void f1() { B::f1(); }
{ cout <<”f1 of A”<<endl; }
}; void f3 ()
{ C:: f1 (); }
class B { };
public :
void f1 () void main () {
{cout <<”f1 of B”<<endl; } D Obj
Obj.f1();
void f2() Obj.f2();
{cout << “f2 of A”<< endl; } Obj.f3();
}; }

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
class C: public A {
// D (int a, int b, int c) : A(a), B(b), C(c). public:
void f3()
Virtual Base Class { cout <<”f3 of c”<<endl; }
class A { };
public:
void f1() class D: public B, public C
{ cout <<”f1 of A”<< endl; } { };
};
void main (){
class B: public A { D obj ;
public: Obj.f1(); //error–f1 is inherited from B & C also
void f2() Obj.f2();
{ cout << “f2 of B”<< endl; } Obj.f3();
}; }

B C

Solution D }

class A {
public : #include <iostream.h>
void f1() #include <string.h>
{ cout <<”f1 of A”<<endl; }
}; class string {
private:
class B: virtual public A { char *str;
public :
void f2 () public:
{ cout <<”f2 of B”<<endl; } string();
}; string(char*);
string operator =(char *);
class C: virtual public A { string operator +(char *);
public: string operator +(string);
void f3() char *get ();
{ cout <<”f3 of c”<<endl; } char *touppercase ();
}; char *tolowercase();
char *totitlecase();
class D: public B, public C int length();
{ }; int charAt(int);
~ string ();
void main () { };
D obj;
Obj.f1(); string :: string ()
Obj.f2(); { str = NULL; }
Obj.f3();

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
string :: string (char *p) {
str = new char [strlen(p)+1]; string string::operator +(char *P) {
strcpy (str, p); } char * temp = new char [strlen(str) + strlen(p)+1];
for (int i = 0; str [i] !=‘\0; i++)
string string::operator = (char *p) { { temp [i] = str [i]; }
if (str != NULL) for(int j=0; p[j] ! = ‘\0’; j++, i++)
delete str; { temp [i] = p[j]; }
str = new char[strlen(p)+1]; temp [i] = ‘\0’;
strcpy (str, p); string *s = new string(temp);
return * this; } return * s; }

char * string :: get () string string::operator +(string t) {


{ return str; } char * temp = new char[strlen(str) + strlen(t,str)+1];
for (int i = 0; str [i]! = ‘\0’; i++)
char * string :: touppercase () { temp [i] = str [i]; }
{ return strupr(str); } for (int j = 0; t.str[j] !=‘\0’; j++, i++)
{ temp [i] = t.str[j]; }
char * string :: tolowercase () temp[i] = ‘\0’;
{ return strlwr(str); } string * s = new string (temp);
char * string :: totitlecase () { return *s; }
char * temp = new char[strlen(str)+1];
strcpy (temp, str);
for (int i = 0; temp [i] !=‘\0’; i++) { #include <iostream.h>
if ((i = = || temp [i-1] = = ‘’ || temp [i-1] = = ‘\t’) #include <conio.h>
&& (temp [i] > = ‘a’ && temp [i] < = ‘z’)) #include”c:/cprog/string.cpp”
temp [i] - = 32;
else if (temp [i] > = ‘A’ && temp [i] < = ‘z’) void main() {
temp [i] + = 32; string s=“hello world”;
} string s2=“ to you”;
return temp; } clrscr();
cout << s.get()<<endl;
int string :: length() cout << s.to upper case ()<<endl;
{ return strlen(str); } cout<<s.to lower case () <<endl;
cout <<s.to title case () << endl;
int string :: charAt(int i) { cout << s.length () << endl;
if (i < 0 || i> str len (str)-1) cout << (char) s.charAt(6) << endl;
return – 1; string s3;
else s3 = s + s2;
return str[i]; } coudt << s3.get()<<endl;
s3 = s + ”to everybody”;
string :: ~string () { cout << s3.set () <<endl;
if (str ! = NULL) }
delete str; }

Pointer to the objects - Similar to primitive data type for user defines data type we can also define pointer, which
occupied two bytes in m/r and can store same class objects. To access member of object we use arrow operator.

length *l;
L = new length;
l->setdata(10,50);
l->showdata();

pointer of a class can store address of same class object or object of the classes which derived from It.

A*P B*P C*P D*P A


P = New A Write Wrong Wrong Wrong
P = New B Write Write Wrong Wrong
P = New C Write Wrong Write Wrong
B C
K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4

D
P = New D Write Write Wrong Write

class A {
public :
void f1 ()
{ cout <<”f1 of A”<<endl; }
vpod f2()
{ cout <<”f2 of A” <<endl; }
};

If base class pointer store address of derived class object we can access only those member of object which comes from
base class, newly added or modified features can not access by base class pointer.

class B: public A { public:


public: void f1()
void f1() {cout <<”f1 of A”<<endl; }
{ cout << “f1 of B”<,endl; }
void f2()
void f3() { cout <<”f2 of A”<<endl; }
{ cout <<”f3 of B”<<endl; } };
};
class B: public A {
void main () { public :
A *a; void f1()
B *b; { cout <<”f1 of B” <, endl; }
b = new B; };
b -> f1(); //f1 of B
b -> f2(); //f2 of A void main () {
b -> f3(); //f3 of B A*a;
a = b; B*b;
a -> f1(); //f1 of A a = new A; //f1 of A
a → f2(); //f2 of A a -> f1 (); //f2 of A
a -> f3(); //error of compilation there a -> f2();
} a = new b;
a -> f1(); //f1 of B
Virtual Functions a -> f2(); //f2 of A
}
class A {

A virtual function is a function of base class which should be override in derived class. If base class pointer stored
address of derived class object and we call the method which is declared virtual in base class and override in derived
class, calling of such function with pointer will not call base class method but override method will be called.
If virtual function is defined with null body It is known as pure virtual function.
For example – virtual void f1() = 0;
A class containing one or more pure virtual function is called abstract class. An abstract class can not be instantiated only
reference or pointer of the class can be declared. An abstract class is used for inheritance and a class which inherited
from abstract class must override virtual function of base class. Abstract class and virtual function provide a new king of
binding that is “dynamic binding” and use of this is for run time polymorphism.
Static Binding and Dynamic Binding - Linking of function calling with function body is binding and there are two
types of binding.
Static Binding - Also known as compile time binding or early binding. This is a default type of binding supported by c+
+. In this conventional type of binding, during compilation compiler (linker) writes function body address wherever
function has called. So at the time of execution the addressed function will be called.
Dynamic Binding - It is also known as runtime binding or late binding. In this new type of binding during compilation
the function and function calling is not link by addresses, but they linked when program is executed.
In c++ dynamic binding can be achieved by abstract classes and virtual function, this gives great flexibility in program.
Several new generation programming concept like DLL, OLE and Active-X are the result of dynamic binding.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
class point { int z;
private: public:
int x, y; point3D() //All initialized with zero
public: { z = 0; }

point () point3D(int x, int y, int z): point (x, y)


{ x = 0, y = 0; } { point 3D :: Z = z; }

point (int x, int y) { void set (int x, int y, int z)


point :: X = x; { set (x, y); point 3D :: Z = z; }
point :: Y = y; }
void show() {
void set (int x, int y) { point :: show (); //overriding
point :: X = x; cout <<z<<endl; }
point :: Y = y; } };

void show () { void main() {


cout <<x<<endl; point3D pt;
cout<<y<<endl; } pt.set(1,1,2);
}; pt.set(1,2);
pt.show ();
class point3D: public point { pt.point::show();
private : }
Constructor in Inheritance - By default derived class constructors calls base class no arguments constructor before
executing its body. But if we want that derive class constructor should call constructor of Base class other than no
argument, we have to do It explicitly by following syntax.

Derive class constructor (argument list): public :


Base class constructor (argument list) Virtual void draw () = 0;
{ };
-------
------- class line : public shape {
} public :
void draw()
Example. { cout <<”line”<<endl; }
class A { };
public :
A() class box : public shape {
{ cout <<”In A”<<endl; } public:
}; void draw()
class B: public A { { cout <<”Box”<<endl; }
public : };
B()
{ cout <<”In B”<< endl; } class circle : public shape {
}; public:
class C: public B { void draw()
public: { cout << “circle”<<endl; }
c() };
{ cout <<”In C”<<endl; }
}; void main () {
void main () { shape *s;
C obj; int i;
} cout <<”\n 1. line \n 2. Box \n 3. circle”<<endl;
cout << “\n enter your choice : ”;
Output: cin>>i;
In A switch (i) {
In B case 1:
In C s = new line;
break;
Multiple Inheritance case 2:
class shape { s = new box;

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
break; exit(1);
case 3: }
s= new circle; s->draw ();
break; }
default :

Advance Features in C++ :

1. Bool data type


2. Templates
3. Exception handling
4. RTTI (Run Time Type Identification)
5. Name Space
Bool Data Type - A new version of C++ Bool Data Type was introduced to store Boolean values true and false. In
earlier versions we use int data type for storing Boolean type values. There new keywords Bool, true, false is introduced
in C++.

Ex. Bool Choice


Choice = false;

Boolean values can be type casted into integer values and vice – versa
Int i;
I = choice; (‘0’)

Name Space - Name space is defined as group of class functions global variables etc. It may be possible that name of the
class or functions and global variables may create conflict with other existing one. To solve this problem concept of
name space is introduced. Name spaces delimited the scope. Two classes in a single name space can not have same name
but in two different name spaces name of classes may be same.

Namespace <name space name>


{
class A
{
-------
-------
}
class B
-------
-------
}
};

When we use any class

It will be looked in current name space and to access class function or variable of other name space we use following
Syntax :
Name space name :: class/function/variable name
n1 :: A

Using - If our program includes different references to the members of name spaces, having to specify name spaces
always with members becomes a difficult task. We can use ‘using’ keyword in such situation. With ‘using’ keyword we
specify name of name spaces and whenever a class, function is refer first C++ look for that in current scope or name
spaces and after that in the name space specified with ‘using’.

Name space Std- Standard C++ defines its entire library in its own name space called std.

RTTI - RTTI is not found in non-polymorphism language. However in polymorphism languages such as C++ there can
be situations in which the type of an object is unknown at compile time because the precise nature of that object is not
determined until the program is executed. This determination must be made at runtime using RTTI.

To obtained an objects type. Used ‘type id’. You must include the header <type info> in order to use type id.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
Syntax : type id (object)
Typed returns a reference to an object of type. Type_info that describes the type of object.

The type_info class defines the following Public members

Bool operator = = (const type_info & obj);


Const + char * name ()

Ex. Int i;
Float j;
Cout << type id (i)name();
Typeid (i) = = typeid(j)

Templates - The template is one of C++ most sophisticated and high power feature. Templates provide a way to write a
logic independent of data types. Using templates It is possible to create generic function & classes. In a generic function
and class the type of data upon which the function of class operates is specified as parameter. Thus you can use are
function or class with several different types of data without having two explicitly recode specific versions for each data
type.

Generic Function - A generic function defines a general set of operation that will applied to various types of data.
Through a generic function a single general procedure can be applied to a will range of data, By creating a generic
function we can define the nature of the algorithm independent of any data.

Once you have done this the compiler will automatically generates the correct code for the type of data that is actually
used when you execute the function.

Template <class type> re_type funct_name (parameter


list) void main () {
{ int a = 10, b = 12;
------- // body of function float x = 1.7, y = 7.4;
} swap (a, b);
cout <<a<<b<<endl;
Example: swap(x, y);
Template <class x> void swap (x &a, x &b) { cout <<x<<y<<endl;
x c; }
c = a; a = b; b = c; }

Generic Classes - It is useful when a class uses logic that can be generalized.

Template <class class name> }


{
------- x pop() {
------- if (top == -1)
}; cout <<”Stack empty: underflow ”;
else
Example: return arr [i--]; }
template <class x> class stack { };
x arr[10];
int top; void main() {
public: stack<int> a;
stack() a.push(10);
{ top = -1; } a.push(20);
cout <<a.pop()<<a.pop<<endl;
void push (x val) { stack<float>b;
if (top = = 9) b.push(1.7);
cout <<”\n stack full : overflow”; cout<<b.pop();
else }
arr[++i] = val;

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4
Exception Handling - Like all other 4GL C++ also supports exception handling, It is a method to handle exception in a
better manner. In C style exception handling exception is handed where exception raised but in C++ if exception raised It
will be transferred to the exception handling module, so the place where exception raised and the place where exception
handle is different.

Following are the advantage of using e.x.

1. Its improve readability of program.


2. Minimize the need of handling exception at multiple places.
3. Increase reliability of program.
4. Provide structured approach of error handling.

In c++ E.H. is introduced after version two.


Syntax –
try
{
-------
-------
}
catch (exception type error)
{
-------
-------
}
catch()
{
-------
-------
}
In try block we write the executable body in which exception is probable and the try block is followed by “n” no. of catch
statements. Each catch statement can handle a special data type exception. Exception can be of primitive data type or
user defined data type for each of the probable exception type in try block we write a catch block. In which we write the
body which to be executed if exception raised.
If exception raised and It is catch by any of catch statement It means exception is catch and handle but if raised exception
type does not match with catch argument type then program terminates during execution.
If we want to write a catch statement which can handle exception of any data type. It is possible by this.

catch (. . .)
{
-------
-------
}

If user want to raised exception explicitly It is possible by using keyword “ throw”.


Syntax throw exception;
Throw statement can be used only within try block.

K - 1 5 , K a n t i E n c l a v e , S i t e N o . 1 , C i t y C e n t e r , G w a l i o r . M . P .
P h o n e N o . : 0 7 5 1 - 2 2 3 2 2 3 1 , 5 0 1 0 4 2 4 / 2 5 , 9 8 2 7 0 1 4 7 3 4

Vous aimerez peut-être aussi