Vous êtes sur la page 1sur 121

Object oriented programming

with C++
Software Crisis
• New approaches in the s/w design
– Dynamic development in technology
– Quick emergence of new tools and technologies
• Increasing complexity of software system
• Highly competitive s/w industry
Other problems
• Representation of real life entities in system
design
• Design system with open interfaces
• Ensure reusability ,extensibility, correctness,
portability, security, integrity, user friendliness
• Modules tolerant to changes
• Improve s/w production and reduce cost
• Improve quality
Evolution
• Modular programming
• Structured programming
• Top down programming
• Bottom up programming
• Functional programming
– Fail to produce the desired result of bug free, easy
to maintain and reusable programs.
“As complexity increase, architecture dominates
the basic material” –alan kay
• Necessitates incorporation of sound
construction techniques and program
structures that are easy to comprehend,
implement and modify
Procedure oriented programming

Pop
• Emphasis is on doing things (algorithms)
• Programs are divided into smaller units called
functions.
• Most of the functions share global data
• Data move openly around the system from
function to function.
• Function transforms data from on form to another.
• Top down approach.
Pop vs oop

Object oriented programming
• Emphasis is on data rather than procedures
• Programs are divided into objects
• Data structures are designed such that they
characterize the objects.
• Functions that operate on the data are tied
together in the Data structure
• Data is hidden and cannot be accessed by
external functions
• Objects may communicate with each other through
functions
• New data and functions can be easily added whenever
necessary.
• Bottom up approach in program design .
• “Approach that provides a way of modularizing
programs by creating partitioned memory area for
both data and functions that can be used as templates
for creating copies of such modules on demand”
Basic concepts
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Car example

benefits
• Eliminates redundancy and extends reuse
• Saves dev time leads to productivity.
• Builds secure programming
• Maps object in the problem domain to
programs
• Easily scalable from small to large
• Complexity can be easily managed.
Applications
• Real time systems
• Simulation and modelling
• Object oriented databases
• AI and expert systems
• Parallel programming and neural networks
• Office automation and cad/cam tools
A simple C++ program
• Comments
• Output operator
• Iostream file
• Namespace
• Return type
Sample program
#include <iostream>
using namespace std;

int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;

cout << "Enter two integers: ";


cin >> firstNumber >> secondNumber;

// sum of two numbers in stored in variable sumOfTwoNumbers


sumOfTwoNumbers = firstNumber + secondNumber;

// Prints sum
cout << firstNumber << " + " << secondNumber << " = " <<
sumOfTwoNumbers;

return 0;
• Input operator
• Variables
• Cascading of I/o operators
// classes example
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
Structure of C++ program
Tokens expressions and control structures

Tokens
• Smallest individual units in a program
– Keywords
– Identifiers
– Constants
– Strings and operators
• Keywords
– Explicitly reserved identifiers and cannot be used
as names for variables or user defined program
elements
Basic Data Type
Functions
• Argument Passing
– Pass by value
– Pass by reference
– Pass by address
• Inline Function
– C++ provides an inline functions to reduce the
function call overhead.
– Inline function is a function that is expanded in
line when it is called.
– When the inline function is called whole code of
the inline function gets inserted or substituted at
the point of inline function call.
– This substitution is performed by the C++ compiler
at compile time.
– Inline function may increase efficiency if it is small.
– in lining is only a request to the compiler, not a
command.
– Compiler can ignore the request in such
circumstances like:
• If a function contains a loop. (for, while, do-while)
• If a function contains static variables.
• If a function is recursive.
• If a function return type is other than void, and the
return statement doesn’t exist in function body.
• If a function contains switch or goto statement.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
//Output: The cube of 3 is: 27
Function overloading
• Function overloading is a feature in C++ where
two or more functions can have the same
name but different parameters.
• Function overloading can be considered as an
example of polymorphism feature in C++.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;

cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
• In C++ programming, you can provide default
values for function parameters.
• . If a function is called by passing argument/s,
those arguments are used by the function.
• But if the argument/s are not passed while
invoking a function then, the default values are
used.
• Default value/s are passed to argument/s in the
function prototype.
Default arguments
#include <iostream>
using namespace std;
void display(char = '*', int = 1);
int main()
{
cout << "No argument passed:\n";
display();
cout << "\nFirst argument passed:\n";
display('#');
cout << "\nBoth argument passed:\n";
display('$', 5);
return 0;
}

void display(char c, int n)


{
for(int i = 1; i <= n; ++i)
{
cout << c;
}
cout << endl;
}
Recursive function
• A function that calls itself is known as recursive
function. And, this technique is known as
recursion.
• The recursion continues until some condition is
met.
• To prevent infinite recursion, if...else
statement (or similar approach) can be used
where one branch makes the recursive call and
other doesn't.
#include <iostream>
using namespace std;
int factorial(int);
int main()
{ int n;
cout<<"Enter a number to find factorial: ";
cin >> n;
cout << "Factorial of " << n <<" = "<<factorial(n);
return 0;
}
int factorial(int n)
{
if (n > 1) {
return n*factorial(n-1);
}
else
return 1;
}
Direct recursion vs indirect recursion
• Direct recursion: When function calls itself, it is
called direct recursion,
– the example we have seen above is a direct
recursion example.
• Indirect recursion: When function calls another
function and that function calls the calling
function, then this is called indirect recursion.
– For example: function A calls function B and
Function B calls function A.
#include <iostream> int fb(int n)
{
using namespace std;
if(n<=1)
int fa(int); return 1;
int fb(int); else
int fa(int n) return n*fa(n-1);
{ }

if(n<=1) int main()


return 1; {
else int num=5;
return n*fb(n-1); cout<<fa(num);
return 0;
}
}
Recursive program to find n^k
#include <iostream>
int power(int n, int k)
using namespace std;
int power(int n, int k); {
if (n == 0)
int main() return 1;
{ else if (n == 1)
int x, y;
return 1;
cin >> x >> y;
cout << power(x, y) << else
endl; return n * power(n, k-
return 0; 1);
} }
Enumeration in C++
• Enum is a user defined data type where we
specify a set of values for a variable and the
variable can only take one out of a small set of
possible values.
– enum direction {East, West, North, South}dir;

• Here Enumeration name is direction which can


only take one of the four specified values, the dir
at the end of the declaration is an enum variable.
Simple enum Example
#include<iostream>
using namespace std;
enum direction {East, West, North, South} dir;
int main()
{
dir = West;
cout<<dir;
return 0;
}
#include <iostream>
using namespace std;
enum direction {East, West, North, South}; int
main()
{
direction dir;
dir = South;
cout<<dir;
return 0;
}
Why use enum in C++
• Enums are used only when we expect the
variable to have one of the possible set of
values,
– Since we have four directions, this variable can
take any one of the four values, if we try to assign
a another random value to this variable, it will
throw a compilation error.
– This increases compile-time checking and avoid
errors that occurs by passing in invalid constants.
• Another important place where they are used
frequently are switch case statements,
– where all the values that case blocks expects can
be defined in an enum.
– This way we can ensure that the enum variable
that we pass in switch parenthesis is not taking
any random value that it shouldn’t accept.
How to change default values of Enum
#include <iostream>
using namespace std;
enum direction {East=11, West=22, North=33, South=44};
int main()
{
direction dir;
dir = South;
cout<<dir;
return 0;
}
Constants
• Constant is something that doesn't change.
– In C and C++ we use the keyword const to make
program elements constant.
– const keyword can be used in many contexts in a
C++ program. It can be used with:
• Variables
• Pointers
• Function arguments and return types
– If you make any variable as constant,
using const keyword, you cannot change its value.
– the constant variables must be initialized whi
int main
{
const int i = 10;
const int j = i + 10; // works fine
i++; // this leads to Compile time error
}
Pointers with const keyword
• Pointers can be declared using const keyword
– Pointer to a const variable
– const Pointer
Pointer to a const variable
• This means that the pointer is pointing to a const variable.

• const int* u;
– Here, u is a pointer that can point to a const int type
variable.
• char const* v;
– still it has the same meaning. In this case also, v is a
pointer to an char which is of const type.

• Pointers to a const variable is very useful, as this can be used


to make any string or array immutable(i.e they cannot be
changed).
const Pointer
• To make a pointer constant, we have to put
the const keyword to the right of the *.
int x = 1;
int* const w = &x;
– Here, w is a pointer, which is const, that points to
an int.
– we can't change the pointer, which means it will
always point to the variable x but can change the
value that it points to, by changing the value of x.
Classes and Objects
• C Structures : int main()
struct Person {
{ Person p1;
char name[50]; cout << "Enter Full name: ";
int age; cin.get(p1.name, 50);
float salary; cout << "Enter age: ";
}; cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
Limitation of C strucutres
• C does not allow the struct data type to be
treated like the built in data type.
– Cannot add or subtract struct type variables.
• They do not permit data hiding
– Easily accessible by variables anywhere in their
scope.
Structures in C++
• Has expanded the structures capabilities to
suit its OOP philosophy.
• Attempts to bring the user defined type as
close as possible to the built in type.
• Also provides facilities to hide data.
• C++ incorporates all extensions in another
user defined type known as Class.
Classes in C++
• In C++ programming language, a class
describes both the properties (data) and
behaviors (functions) of objects.
• C++, the data and functions (procedures to
manipulate the data) are bundled together as
a self-contained unit called an object
• Classes are not objects, but they are used to
instantiate objects.
• A class is an abstract data type similar to 'C
structure'.
• The Class representation of objects and the
sets of operations that can be applied to such
objects.
• The class consists of Data members and
methods.
• The primary purpose of a class is to hold
data/information. This is achieved with
attributes which are also known as data
members.
• The member functions determine the
behavior of the class i.e. provide a definition
for supporting various operations on data held
in form of an object.
Class class_name
{
Data Members;
Methods;
}
class A {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}
• Private, Protected, Public is called visibility
labels.
• The members that are declared private can be
accessed only from within the class.
• Public members can be accessed from outside
the class also.
• In C++, data can be hidden by making it
private.
Class members
• Data and functions are members.
• Data Members and methods must be declared
within the class definition.
• A member cannot be redeclared within a
class.
• No member can be added elsewhere other
than in the class definition.
Class A
{
int i;
int j;
void f (int, int);
int g();
}
Accessing the Data Members
• The public data members of objects of a class
can be accessed using the direct member
access operator (.).
// box 2 specification
Box2.height = 10.0;
#include <iostream>
Box2.length = 12.0;
using namespace std; Box2.breadth = 12.0;
class Box { // volume of box 1
public:
double length; // Length of a box
volume = Box1.height * Box1.length *
double breadth; // Breadth of a box Box1.breadth;
double height; // Height of a box cout << "Volume of Box1 : " << volume
}; <<endl;
int main( ) {
// volume of box 2
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box volume = Box2.height * Box2.length *
double volume = 0.0; // Store the volume of a box Box2.breadth;
here cout << "Volume of Box2 : " << volume
// box 1 specification
<<endl;
Box1.height = 4.0;
Box1.length = 6.0; return 0;
Box1.breadth = 3.0; }
#include <iostream>
using namespace std; void display()
class stud { {
public: cout<<"\nAge\tName\tR.No.\tClass";
char name[30],clas[10]; cout<<"\n"<<age<<"\t"<<name<<"\t"<
int rol,age; <rol<<"\t"<<clas; }
void enter() };
{
cout<<"Enter Student Name: "; int main()
cin>>name; {
cout<<"Enter Student Age: "; cin>>age;
class stud s;
cout<<"Enter Student Roll number: "; s.enter();
cin>>rol; s.display();
cout<<"Enter Student Class: ";
cin>>clas;
cin.get();
}
//use this to wait for a keypress }
Constructors and destructors
• C++ provides a special member function called
the constructor which enables an object to
initialize itself at the time of its creation.
• This is known as automatic initialization of
objects.
• This concept of C++ also provides another
member function called destructor which is
used to destroy the objects when they are no
longer required
• A class constructor is a special member function
of a class that is executed whenever we create
new objects of that class.
• A constructor will have exact same name as the
class and it does not have any return type at all,
not even void.
• If we do not specify a constructor, C++ compiler
generates a default constructor for us (expects
no parameters and has an empty body).
• t is named as "constructor" because it
constructs the value of data member of a
class.
• Initial values can be passed as arguments to
the constructor function when the object is
declared.
Special characteristics of Constructors:
• They should be declared in the public section
• They do not have any return type, not even void
• They get automatically invoked when the objects are
created
• Like other functions, they can have default arguments
• They cannot be inherited though derived class can
call the base class constructor
• You cannot refer to their address
• Constructors cannot be virtual
Types of constructors
• Default constructor
– The default constructor is the constructor which
doesn't take any argument. It has no parameter
but a programmer can write some initialization
statement there.
– A default constructor is very important for
initializing object members, that even if we do not
define a constructor explicitly, the compiler
automatically provides a default constructor
implicitly.
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
• Parameterized constructor
– It is possible to pass arguments to constructors.
– these arguments help initialize an object when it is
created.
– To create a parameterized constructor, simply add
parameters to it the way you would to any other
function.
– When you define the constructor’s body, use the
parameters to initialize the object.
• Copy constructor
#include<iostream>
using namespace std;

class Point
{
private: int main()
int x, y; {
public: // Constructor called
// Parameterized Constructor Point p1(10, 15);
Point(int x1, int y1)
{ // Access values assigned by
x = x1; constructor
y = y1; cout << "p1.x = " << p1.getX()
} << ", p1.y = " << p1.getY();

int getX() return 0;


{ }
return x;
}
int getY()
{
return y;
}
};
Destructors
• destructors are used to destroy the objects that have
been created by the constructor within the C++ program.
• Destructor names are same as the class name but they
are preceded by a tilde (~).
• It is a good practice to declare the destructor after the
end of using constructor.
• The destructor neither takes an argument nor returns any
value and the compiler implicitly invokes upon the exit
from the program for cleaning up storage that is no longer
accessible.
class A int main()
{ {
A() A obj1; // Constructor Called
{ int x=1;
cout << "Constructor called"; if(x)
} {
~A() A obj2; // Constructor
{ Called
cout << "Destructor called"; } // Destructor Called for
obj2
}
} // Destructor called for obj1
};
Static data members
• We can define class members static
using static keyword
• A static member is shared by all objects of the class.
All static data is initialized to zero when the first
object is created, if no other initialization is present.
• We can't put it in the class definition but it can be
initialized outside by redeclaring the static variable,
using the scope resolution operator :: to identify
which class it belongs to.
#include <iostream> private:
double length; // Length of a
using namespace std; box
double breadth; // Breadth of
a box
class Box {
double height; // Height of a
public: box
static int objectCount; };

// Constructor definition // Initialize static member of class


Box
Box(double l = 2.0, double b = 2.0, double h =
2.0) { int Box::objectCount = 0;
cout <<"Constructor called." << endl;
int main(void) {
length = l;
Box Box1(3.3, 1.2, 1.5); //
breadth = b;
Declare box1
height = h;
Box Box2(8.5, 6.0, 2.0); //
Declare box2
// Increase every time object is created
objectCount++; // Print total number of objects.
} cout << "Total objects: " <<
double Volume() { Box::objectCount << endl;
return length * breadth * height;
} return 0;
}
• By declaring a function member as static, makes it
independent of any particular object of the class.
• A static member function can be called even if no
objects of the class exist and the static functions
are accessed using only the class name and the
scope resolution operator ::.
• A static member function can only access static
data member, other static member functions.
#include <iostream> private:
double length; // Length of a box
using namespace std; double breadth; // Breadth of a box
double height; // Height of a box
class Box { };
public:
static int objectCount; // Initialize static member of class Box
int Box::objectCount = 0;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) { int main(void) {
cout <<"Constructor called." << endl; // Print total number of objects before creating
length = l; object.
breadth = b; cout << "Inital Stage Count: " << Box::getCount() <<
height = h; endl;

// Increase every time object is created Box Box1(3.3, 1.2, 1.5); // Declare box1
objectCount++; Box Box2(8.5, 6.0, 2.0); // Declare box2
}
double Volume() { // Print total number of objects after creating object.
return length * breadth * height; cout << "Final Stage Count: " << Box::getCount() <<
} endl;
static int getCount() {
return objectCount; return 0;
} }
Case 1:Friend functions
• A friend function is a function that can access the
private members of a class as though it were a
member of that class.
• A friend function may be either a normal function,
or a member function of another class.
• To declare a friend function, simply use
the friend keyword in front of the prototype of the
function you wish to be a friend of the class.
/* C++ program to int func(Distance d){
demonstrate the working of //function definition
friend function.*/ d.meter=10; //accessing private data
from non-member function
return d.meter;
#include <iostream> }
using namespace std;
int main(){ Distance D;
cout<<"Distace: "<<func(D);
class Distance { system("pause");
private: return 0;
}
int meter;
public:
Distance(): meter(0){ }
friend int
func(Distance); //friend
function
};
Case 2:Multiple friends
• A function can be a friend of more than one
class at the same time
– PrintWeather is a friend of both classes, it can access
the private data from objects of both classes.
– class prototype that tells the compiler that we are
going to define a class called Humidity in the future.
– Without this line, the compiler would tell us it
doesn’t know what Humidity is when parsing the
prototype for PrintWeather() inside the Temperature
class.
class Humidity;

class Temperature
{
private:
int m_temp;
public:
Temperature(int temp=0) { m_temp = temp; }

friend void printWeather(const Temperature &temperature, const Humidity &humidity);


};

class Humidity
{
private:
int m_humidity;
public:
Humidity(int humidity=0) { m_humidity = humidity; }

friend void printWeather(const Temperature &temperature, const Humidity &humidity);


};
void printWeather(const Temperature &temperature, const Humidity &humidity)
{
std::cout << "The temperature is " << temperature.m_temp <<
" and the humidity is " << humidity.m_humidity << '\n';
}

int main()
{
Humidity hum(10);
Temperature temp(12);

printWeather(temp, hum);

return 0;
}
Case 3: Friend member functions
• Instead of making an entire class a friend, you
can make a single member function a friend.
• This is done similarly to making a normal
function a friend, except using the name of
the member function with the className::
prefix included
– (e.g. Display::displayItem).
class Storage; // forward declaration for class Storage
class Display
{
private:
bool m_displayIntFirst;

public:
Display(bool displayIntFirst) { m_displayIntFirst = displayIntFirst; }
void displayItem(Storage &storage); // forward declaration above needed for this declaration line
};

class Storage // full definition of Storage class


{
private:
int m_nValue;
double m_dValue;
public:
Storage(int nValue, double dValue)
{
m_nValue = nValue;
m_dValue = dValue;
}

// Make the Display::displayItem member function a friend of the Storage class (requires seeing the full declaration of class Display,
as above)
friend void Display::displayItem(Storage& storage);
};
// Now we can define Display::displayItem, which needs to have seen the full declaration of
class Storage
void Display::displayItem(Storage &storage)
{
if (m_displayIntFirst)
std::cout << storage.m_nValue << " " << storage.m_dValue << '\n';
else // display double first
std::cout << storage.m_dValue << " " << storage.m_nValue << '\n';
}

int main()
{
Storage storage(5, 6.7);
Display display(false);

display.displayItem(storage);

return 0;
}
Friend classes

• It is also possible to make an entire class a


friend of another class. This gives all of the
members of the friend class access to the
private members of the other class.
class Storage
{
private:
int m_nValue;
double m_dValue;
public:
Storage(int nValue, double dValue)
{
m_nValue = nValue;
m_dValue = dValue;
}

// Make the Display class a friend of Storage


friend class Display;
};
class Display
{
private:
bool m_displayIntFirst;

public:
Display(bool displayIntFirst) { m_displayIntFirst = displayIntFirst; }

void displayItem(Storage &storage)


{
if (m_displayIntFirst)
std::cout << storage.m_nValue << " " << storage.m_dValue << '\n';
else // display double first
std::cout << storage.m_dValue << " " << storage.m_nValue << '\n';
}
};

int main()
{
Storage storage(5, 6.7);
Display display(false);

display.displayItem(storage);

return 0;
}
Passing objects as arguments
• The objects of a class can be passed as arguments to member
functions as well as nonmember functions either by value or by
reference.
• When an object is passed by value,
– a copy of the actual object is created inside the function. This copy is
destroyed when the function terminates. A
– Any changes made to the copy of the object inside the function are not
reflected in the actual object.
• In pass by reference,
– only a reference to that object (not the entire object) is passed to the
function.
– changes made to the object within the function are also reflected in the
actual object.
• Whenever an object of a class is passed to a
member function of the same class, its data
members can be accessed inside the function
using the object name and the dot operator.
• However, the data members of the calling
object can be directly accessed inside the
function without using the object name and
the dot operator.
#include<iostream.h> void weight :: putdata ()
class weight {
{ cout<<kilogram<<" Kgs. and"<<gram<<"
gros.\n";
int kilogram;
}
int gram; void weight :: sum_weight(weight
public: wl,weight w2)
void getdata (); {
void putdata (); gram = wl.gram + w2.gram;
void sum_weight (weight,weight) ; kilogram=gram/1000;
gram=gram%1000;
};
kilogram+=wl.kilogram+w2.kilogram;
void weight :: getdata() }
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
int main ()
w3.sum_weight(wl,w2);
{
cout<<"/n Weight #1 = ";
weight wl,w2 ,w3;
wl.putdata();
cout<<"Enter weight in kilograms
and grams\n"; cout<<"Weight #2 = ";

w2.putdata();
cout<<"\n Enter weight #1" ;
cout<<"Total Weight = ";
wl.getdata();
w3.putdata();
cout<<" \n Enter weight #2" ;
return 0;
w2.getdata();
}
Array of Objects
• an array of a class type is also known as an
array of objects.
• The array of type class contains the objects of
the class as its individual elements.
#include <iostream> int main()
#include <string> {
using namespace std; Student st[5];
class Student for( int i=0; i<5; i++ )
{ {
string name; cout << "Student " << i + 1 << endl;
int marks; cout << "Enter name" << endl;
public:
st[i].getName();
cout << "Enter marks" << endl;
void getName(){
st[i].getMarks();
getline( cin, name );
}
}
void getMarks(){
cin >> marks; for( int i=0; i<5; i++ )
} {
void displayInfo(){ cout << "Student " << i + 1 << endl;
cout << "Name : " << name << endl; st[i].displayInfo();
cout << "Marks : " << marks << endl; }
} return 0;
}; }
“This” pointer
• “When a member function is called, how does C++ keep
track of which object it was called on?”

• The “this” pointer is a hidden parameter implicitly added to


any non-static member function.
• you will not need to access it directly, but you can if needed.
• “this” is a const pointer -- you can change the value of the
underlying object it points to, but you can not make it point
to something else!
class Simple int main()
{
{
private:
int m_id; Simple simple(1);
simple.setID(2);
public: std::cout <<
Simple(int id) simple.getID() << '\n';
{
setID(id);
} return 0;
}
void setID(int id) { m_id = id; }
int getID() { return m_id; }
};
• Let’s examine the mechanics behind how this
works.
simple.setID(2);
• Although the call to function setID() looks like it
only has one argument, it actually has two!
• When compiled, the compiler converts
simple.setID(2); into the following:
setID(&simple, 2);
// note that simple has been changed from an
object prefix to a function argument!
• Since the function call now has an added argument, the
member function definition needs to be modified to accept
(and use) this argument as a parameter. Consequently,
void setID(int id) { m_id = id; }
• is converted by the compiler into:
void setID(Simple* const this, int id) { this->m_id = Id; }
• When the compiler compiles a normal member function, it
implicitly adds a new parameter to the function named “this”.
• The this pointer is a hidden const pointer that holds the
address of the object the member function was called on.
• Putting it all together:
• 1) When we call simple.setID(2), the compiler
actually calls setID(&simple, 2).
• 2) Inside setID(), the *this pointer holds the
address of object simple.
• 3) Any member variables inside setID() are
prefixed with “this->”. So when we say m_id = id,
the compiler is actually executing this->m_id = id,
which in this case updates simple.m_id to id.
Explicitly referencing *this
class Something
{
private:
int data;

public:
Something(int data)
{
this->data = data;
}
};
• if a constructor (or member function) has a
parameter with the same name as a member
variable, you can disambiguate them by using “this”:
• “data” refers to the parameter, and “this->data”
refers to the member variable.
• Although this is acceptable coding practice, using
the “m_” prefix on all member variable names
provides a better solution by preventing duplicate
names altogether!
Constructor Overloading
• Constructor can be overloaded in a similar way as
function overloading.
• Overloaded constructors have the same name (name
of the class) but different number of arguments.
• Depending upon the number and type of arguments
passed, specific constructor is called.
• Since, there are multiple constructors present,
argument to the constructor should also be passed
while creating an object.
#include <iostream> int main()
using namespace std; {
class Area{ Area A1, A2(2, 1);
private: int temp;
cout << "Default Area when no
int length; int breadth;
argument is passed." << endl;
public:
Area(): length(5), breadth(2) { } temp = A1.AreaCalculation();
Area(int l, int b): length(l), breadth(b){ } A1.DisplayArea(temp);
void GetLength() {
cout << "Enter length and breadth "; cout << "Area when (2,1) is passed
as argument." << endl;
cin >> length >> breadth;
} temp = A2.AreaCalculation();
int AreaCalculation() { A2.DisplayArea(temp);
return length * breadth; return 0;
} }
void DisplayArea(int temp){
cout << "Area: " << temp << endl;}
};
Copy constructor
• A copy constructor is a member function which initializes an
object using another object of the same class.
• A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);

• Copy Constructor Declaration In Main Function


// In Main Function
class_name object1(params);

Method 1 - Copy Constrcutor Method 2 - Copy Constrcutor


class_name object2(object1); class_name object3 = object1;
#include<iostream> void Display() {
cout << "\nValues :" << a << "\t" << b;
#include<conio.h>
}
using namespace std; };
class Example {
int a, b; int main() {
//Normal Constructor Invoked
Public:
Example Object(10, 20);
Example(int x, int y) {
a = x; //Copy Constructor Invoked Method 1
b = y; Example Object2(Object);

cout << "\n Im Constructor"; //Copy Constructor Invoked Method 2


}//Copy Constructor with Obj Example Object3 = Object;
Argument
Example(const Example& obj) { Object.Display();
Object2.Display();
a = obj.a;
Object3.Display();
b = obj.b; // Wait For Output Screen
cout << "\nIm Copy getch();
Constructor"; return 0;
}
}
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1;// Copy constructor is called here
Point p3(0,0);
p3=p1;
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
cout << "\np3.x = " << p3.getX() << ", p3.y = " << p3.getY();
return 0;
}
Scope resolution operator in C++
• To access a global variable when there is a
local variable with same name:
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x
is " << ::x;
cout << "\nValue of local x
is " << x;
return 0;
}
To define a function outside a class.
#include<iostream>
using namespace std;
class A
{
public:

// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
To access a class’s static variables.
#include<iostream>
using namespace std;

class Test
{ int Test::x = 1;
static int x; int Test::y = 2;
public:
static int y; int main()
{
// Local parameter 'a' hides class memberTest obj;
// 'a', but we can access it using ::
int x = 3 ;
void func(int x)
{
obj.func(x);
// We can access class's static variable
// even if there is a local variable cout << "\nTest::y = " << Tes
cout << "Value of static x is " << Test::x;
return 0;
cout << "\nValue of local x is " <<
} x;
}
};
In case of multiple Inheritance:
If same variable name exists in two ancestor classes, we can use scope
resolution operator to distinguish.

#include<iostream>
class C: public A, public B
using namespace std;
{
public:
class A
void fun()
{
{
protected:
cout << "A's x is " << A::x;
int x;
cout << "\nB's x is " << B::x;
public:
}
A() { x = 10; }
};
};
int main()
class B
{
{
C c;
protected:
c.fun();
int x;
return 0;
public:
}
B() { x = 20; }
};
Dynamic objects
• Memory for the variables is allocated in two
ways
– Static allocation
• Decision to allocate memory for the variable is taken
during compile time
– Dynamic allocation
• Decision to allocate memory for the variable is taken
during execution
• To allocate memory dynamically “new” operator
is used in C++
• Syntax:
– Pointer= new data_type;

#include<iostream>
int main()
{
int *p;
p=new int;
*p=89;
cout<<*p;
return 0;
}
New operator on any array
#include<iostream>
int main()
{
int n, sum, i ,*p;
cout<<“enter the numner of elements”<<“\n”;
cin>>n;
p=new int [n];
cout<<“enter the array elements”;
for(i=0;i<n;i++)
{
cin>>p[i];
}
sum=0;
for(i=0;i<n;i++)
{
sum=sum+p[i];
}
cout<<“result of adding array elemnets is:”<<sum;
}
Delete operator
• To deallocate the dynamically allocated memory, “delete” operator is
used.
• Syntax
– delete pointer;
#include<iostream>
int main()
{
int *p;
p=new int;
*p=89;
cout<<*p;
delete p;
return 0;

}
#include<iostream>
int main()
{
int n, sum, i ,*p;
cout<<“enter the number of elements”<<“\n”;
cin>>n;
p=new int [n];
cout<<“enter the array elements”;
for(i=0;i<n; i++)
{
cin>>p[i];
}
sum=0;
for(i=0;i<n; i++)
{
sum=sum+p[i];
}
cout<<“result of adding array elements is:”<<sum;
delete[] p;
}
void print()
#include <iostream>
{
#include <string> cout<<"roll no is "<<rollno;
using namespace std; cout<<"name is "<<name;
class student }
};
{
int main ()
private: {
int rollno; student *ps=new student;
string name; (*ps).get();
(*ps).print();
public:
delete ps;
student():rollno(0),name("") return 0;
{} }
student(int r, string n): rollno(r),name (n) ---------------------------------------------------------------
int main ()
{}
{
void get() student ps;
{ student *p;
cout<<"enter roll no"; p=&ps;

cin>>rollno;
p->get();
cout<<"enter name"; p->print();
cin>>name;
} return 0;
}

Vous aimerez peut-être aussi