0% found this document useful (0 votes)
58 views116 pages

Oop Chapter 1

This document provides an overview of Object Oriented Programming (OOP) using C++, including fundamental concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It contrasts procedural programming with object-oriented programming, highlighting the advantages of OOP such as code reusability and data abstraction. Additionally, it outlines the structure of a C++ program and the applications of OOP in various fields.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views116 pages

Oop Chapter 1

This document provides an overview of Object Oriented Programming (OOP) using C++, including fundamental concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It contrasts procedural programming with object-oriented programming, highlighting the advantages of OOP such as code reusability and data abstraction. Additionally, it outlines the structure of a C++ program and the applications of OOP in various fields.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 116

Object Oriented Programming with C++

(CPE2402L01)

Unit 1
Fundamentals of Object Oriented
Programming
Mrs. Sonal Mohite
(Computer Department , DYPCOE)
Contents:
• Difference between procedure oriented(POP) and object oriented
programming (OOP)
• Basic concepts of object oriented programming in C++
• C++ programming-classes, objects, array of objects, member functions,
access specifiers, friend function, friend class, static variables, static
function, inline functions, this pointer, namespaces
• Constructor- Types: Default, parameterized, copy, Destructors
Introduction
• C++ is an object oriented programming language.
• C++ is a general purpose, case-sensitive, free-form
programming language that supports object-oriented,
procedural and generic programming.
• C++ is a middle-level language, as it encapsulates
both high and low level language features.
• It is developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murry Hill, New Jersey, USA in
the early 1980's.
• C++ is an extension of C with major addition of the Class
feature.
• Class was a major addition to the original C language.

• Stroustrup initially called the new language


'C with Classes'

• Later in 1983, the name was changed to C++.

• The Most important facilities that C++ adds to C are


Classes, Inheritance, Function Overloading and
Operator Overloading.
Difference between Procedure Oriented
Language(C) and Object Oriented
Language(C++)
• The major difference between C and C++ is that C is a
procedural programming language and does not support
classes and objects.
• while C++ is a combination of both procedural and object
oriented programming language; therefore C++ can be
called a hybrid language.
OOP POP
Object Oriented Structure Oriented

Program is divided into objects. Program is divided into functions.

Bottom-up approach. Top-down approach.

Inheritance property is used. Inheritance is not allowed.

It uses access specifier. It doesn’t use access specifier.

Encapsulation is used to hide the data. No data hiding.

Concept of virtual function. No virtual function.

Object functions are linked through message Parts of program are linked through parameter
passing. passing.

Adding new data and functions is easy Expanding new data and functions is not easy.

The existing code can be reused. No code reusability.

use for solving big problems. Not suitable for solving big problems.

C++, Java C, Pascal.


No. C C++
1) C follows the procedural style C++ is multi-paradigm. It supports
programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.

3) C follows the top-down approach. C++ follows the bottom-up approach.

4) C does not support function C++ supports function overloading.


overloading.
5) In C, you can't use functions in In C++, you can use functions in
structure. structure.
6) C does not support reference variables. C++ supports reference variables.

7) In C, scanf() and printf() are mainly C++ mainly uses stream cin and cout to
used for input/output. perform input and output operations.
8) Operator overloading is not possible in Operator overloading is possible in
C. C++.

9) C programs are divided into procedures C++ programs are divided


and modules into functions and classes.

10) C does not provide the feature of C++ supports the feature of
namespace. namespace.

11) Exception handling is not easy in C. It C++ provides exception handling


has to perform using other functions. using Try and Catch block.

12) C does not support the inheritance. C++ supports inheritance.


Basic Concepts of Object Oriented
Programming
1) Objects
2)Classes
3)Data Abstraction
4)Encapsulation
5)Inheritance
6)Polymorphism
7)Dynamic Binding
8)Message Passing
Object
●Objects are basic run-time entities in an object
oriented system
●Objects are instances of a class
●It is user defined data types.
●Practically each and every living and nonliving
thing is an object
●Any entity that has state and behavior is known
as an object.
●For example: chair, pen, table, keyboard, bike
etc.
● Object take up space in memory and have an
associated address.
ex:
class person
{
//private:
char name[20];
int id;
public:
void getdetails() {........ }
};

void main()
{
person p1, p2; //p1 is a object
}
Class
• Collection of objects is called class.
• Class is a blueprint of data and functions or methods.
• Class does not take any memory space.
• Class is a user defined data type like structures and unions in C.
• By default class variables are private.
• A class contains members like data members and member
functions.
• Data members are variables of the class.
• Member functions are the methods that are used to manipulate
data members.
• Data members define the properties of the class whereas the
member functions define the behaviour of the class.
• A class can have multiple objects which have properties and
behaviour that in common for all of them.
syntax for class:-

class class_name {

data_type data_member_name;

return_type method_name(parameters);

}
*********************************** OR *****************************
class class_name
{
private:
//data members and member functions declarations
public:
//data members and member functions declarations
protected:
//data members and member functions declarations
};
class student{
int rollno;
char name[20];
public:
void get();
void put();
};
void main(){
student s;
s.get();
}
Data Abstraction
• Data abstraction refers to, providing only
essential information to the outside world and
hiding their background details, i.e., to represent
the needed information in program without
presenting the details.

• For example, a database system hides certain


details of how data is stored and created and
maintained. Similar way, C++ classes provides
different methods to the outside world without
giving internal detail about those methods and
data.
• Consider a real life example of a man driving a
car. The man only knows that pressing the
accelerators will increase the speed of car or
applying brakes will stop the car but he does not
know about how on pressing accelerator the
speed is actually increasing, he does not know
about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the
car. This is what abstraction is.

● Example--filling online form, essential


information is shown to user and its background
details are hidden from user
Encapsulation
• Wrapping up of data and functions into a single
unit(called class) is known as encapsulation.
• For example: capsule, it is wrapped with
different medicines.
• The data is not accessible to the outside world
and only those functions which are wrapping in
the class can access it.
• This insulation of the data from direct access by
the program is called data hiding or information
hiding.
Inheritance
• One of the most useful aspects of object-
oriented programming is code reusability.
• As the name suggests Inheritance is the
process of forming a new class from an existing
class
• the existing class called as base class, new
class is called as derived class.
• This is a very important concept of object-
oriented programming since this feature helps to
reduce the code size.
• Inheritance is a way to reuse once written code
again and again. The class which is inherited is
called base class & the class which inherits is
called derived class.

• So when, a derived class inherits a base class,


the derived class can use all the functions which
are defined in base class, hence making code
reusable.
class Animal{
void eat(){..}
void sleep(){..}
};

void Dog :: public Animal{


// use/calling of eat() function
void bark(){..}
}
Polymorphism
• The term "Polymorphism" is the combination of "poly"
+ "morphs" which means many forms. It is a greek
word.
• polymorphism means ability to take more than one
form.
• An operation may exhibit different behaviors in different
instances. The behavior depends upon the types of
data used in the operation.
• C++ supports operator overloading and function
overloading.
+, -, *, /, <, > , 5+3=8
eg--void add(){..} void add(){..} void add(){...}
• Operator overloading is the process of making
an operator to exhibit different behaviors in
different instances is known as operator
overloading.
• Function overloading is using a single function
name to perform different types of tasks.
Dynamic Binding
•In dynamic binding, the code
to be executed in response to
function call is decided at
runtime.
•C++ provides facility to
specify that the compiler
should match function calls
with the correct definition at
the run time; this is called
dynamic binding or late
binding or run-time binding.
•Dynamic binding is achieved
using virtual functions.
Message Passing
• The process of programming in OOP involves
following steps.
1) Creating Classes
2) Creating Objects
3) Establishing communication among objects.
• In simple words message passing is nothing
but the sending and receiving information by
object, same as people pass message to one
another.
• Objects communicate with one another by
sending and receiving information to each other.
• A message for an object is a request for
execution of a function that generates the
desired results.
• Message passing involves specifying the name
of the object, the name of the function and the
information to be sent.
Employee.salary(name);
• Here employee is object, salary is message
and name is information
Object oriented programming
languages
• C++
• C#
• Smalltalk Simula
• Object Pascal
• Eiffel
• Java
• Python
• Ruby
• PHP
APPLICATIONS OF OOPS
• By the help of C++ programming language, we can develop different types of
secured and robust applications:

• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
• Application Software Development
Structure of C++ program
The structure of C++ program is divided into
four different sections:
(1) Header File Section
(2) Class Declaration section
(3) Member Function definition section
(4) Main function section
(1) Header File Section:

---This section contains various header files.


---You can include various header files in to your
program using this section.

For example:
#include<iostream.h>
#include<conio.h>
clrscr();
getch();
---Header file contains declaration and definition
of various built in functions as well as object. In
order to use this built in functions or object we
need to include particular header file in our
program.
(2) Class Declaration Section:

---This section contains declaration of class.


---You can declare class and then declare data
members and member functions inside that class
----You can also inherit one class from another
existing class in this section.
For example:
class Demo
{
int a, b;
public:
void input();
void output();
};
(3) Member Function Definition Section:
---This section is optional in the structure of C++
program.
---Because you can define member functions inside
the class or outside the class. If all the member
functions are defined inside the class then there is no
need of this section.
---This section is used only when you want to define
member function outside the class.
---This section contains definition of the member
functions that are declared inside the class.
For example:
void Demo:: input ()
{
cout << “Enter Value of A:”;
cin >> a;
cout << “Enter Value of B:”;
cin >> b;
}
(4) Main Function Section:

----In this section you can create an object of the


class and then using this object you can call various
functions defined inside the class as per your
requirement.
For example:
void main ()
{
Demo d1; // student s1;
d1.input ();
d1.output ();

}
Scope resolution operator in C++
In C++, scope resolution operator is :: . It is used
for following purposes.

1) To define a function outside a class.


2) To access a class’s static variables.
3) In case of multiple Inheritance.
4) To access a global variable when there is a local variable with
same name.
5) For namespace
6) Refer to a class inside another class.
https://www.geeksforgeeks.org/scope-resolution-operator-in-c/
C++ Object and Class
⮚ Since C++ is an object-oriented language, program is
designed using objects and classes in C++.
❑ C++ Object
• In C++, Object is a real world entity, for example, chair,
car, pen, mobile, laptop etc.
• In other words, object is an entity that has state and
behavior. Here, state means data and behavior means
functionality.
• Object is a runtime entity, it is created at runtime.
• Object is an instance of a class. All the members of the
class can be accessed through object.
❑ C++ Class
• In C++, class is a group of similar objects.
• It is a template from which objects are created. It can
have fields, methods, constructors etc.
• Let's see an example of C++ class that has three fields
only. class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}

• Let's see an example to create object of student class using s1 as the reference variable.

Student s1; //creating an object of Student

• In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.
Classes and Objects
Class Definition:

1. A class is a blueprint for the object.

2. Class is a user-defined data type, which holds


its own data members and member functions,
which can be accessed and used by creating
an instance of that class.
For Example:
Consider the Class of Cars. There may be
many cars with different names and brand
but all of them will share some common
properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc.
So here, Car is the class and wheels,
speed limits, mileage are their properties
(data member) and member functions can
be apply brakes, increase speed etc.
●A class specification has two parts:
1) Class Declaration
2) Class function definition
• The keyword class specifies, that class_name
• Body of a class is enclosed within braces and
terminated by semicolon.
• Class body contains declaration of variables
and functions
• These variabes are collectively called as class
members
• The keyword PUBLIC and PRIVATE are known
as visibility labels/modes
• Default visibility mode is PRIVATE.
What is Class in C++
• A class is a way to bind data and its associated
function together.
• It allows the data and function to be hidden, if
necessary.
• When defining class we are creating new abstract
data type that can be treated as other built-in
data type
Example
Creating Object
Syntax
Class_name object_name;
Example: item x;
OR
item x,y,z ; //multiple object

We can also create object after class declaration as


we do for structures(i.e declaring after semicolon)
Defining member function
Member function can be defined in two different
way:
(1) Inside class
(2) Outside class
(1) Inside Class:

When we declare the function in the class at the same


time we can also give the definition of the function in
the class as shown below:
class Test{
int a,b;
public:
void input (){
cout<<"Enter Value of a and b";
cin>>a>>b;
}
};

The function defined inside class becomes inline by


default.
Outside definition:
• An important difference between a member
function and normal function is that a member
function incorporates a membership ‘identity
label’ in the header i.e class_name::
• This ‘label’ tells the compiler which class the
function belongs to.
Syntax
Example
class student{
int rollno;
float mark;
public:
void get();
void put(){
cout<<rollno<<marks;
} };
void student :: get(){
cin>>rollno>>marks;
}
class A{
public: void get(); }
class B{
public: void get(); }
void A :: get() {......}
void B :: get() {...........}
void main(){
A a; B b;
a.get();
b.get();
}
Characteristics of Member function are:
• Several different classes can use the same
function name. the membership label will
resolve their scope.
• Member function can access private data of the
class
• The member function can call another member
function directly, without using the dot operator
Inside class definition:
• Another method of defining member function is
to replace the function declaration by the actual
function definition.
• When function is defined inside class is called as
inline function
• Normally small functions are defined inside a
class.
class Test
{
int a,b;
public:
void input ()
{
cout<<"Enter Value of a";
cin>>a>>b;
}
};
Inline Function
● One of objective of using functions in a program is to save
memory space.
● Every time a function is called, it takes a lot of extra time in
executing a series of tasks such as jumping to the function,
pushing arguments, returning to calling function.
● C++ has solution to this problem—inline finction.
● An inline function is a function that is expanded in line
when it is invoked.
● That is compiler replaces the function call with the
corresponding function code.
Making outside function inline:
when we define member function outside the
class definition and still make it inline by just using
the qualifier inline in the header line of function
definition
Accessing class members
●Private members of a class can be accessed by
member functions of that class.
●Syntax for calling public members
object_name.function_name(actual_arguments);
eg.-- x.getdata(100,12.25);
x.rollno=10;
#include<iostream.h>
#include<conio.h>
class student{
int rollno;
void get();
public:
int marks;
void put();
};
void student::get(){
rollno=5;
marks=88;
}
void student::put(){
get();
cout<<rollno;
cout<<marks;
}
void main(){
student s;
s.rollno=5; //error
s.marks=88;
s.get(); //error
s.put();
}
●Members declared as public can be accessed by
objects.
●A private member function can be called by
another function that is a member of its class.
●An object cannot invoke a private function
using the dot operator
Prg1- WAP to declare a class 'student' having data members
as stud_id, name, roll_no. Accept and display this data for
one object.
#include<iostream.h>
#include<conio.h>
class student{
int stud_id, roll_no;
char name[30];
public:
void getdata();
void putdata();
};
void student::getdata(){
cout<<”Enter student ID, roll number and name”;
cin>>stud_id>>roll_no>>name;
}
void student :: putdata(){
cout<<”\n Student ID”<<stud_id;
cout<<”\n Student Roll Number”<<roll_no;
cout<<”\n Student Name”<<name;
}
void main(){
student s;
clrscr();
s.getdata();
s.putdata();
getch();
}
Prg 2-- WAP to declare a class 'Journal' having data members as
journal_nm, price, ISSN_No. Accept this data for two objects
and display the name of journal having greater price.
#include<iostream.h>
#include<conio.h>
class journal{
public:
char journal_nm[20];
int price, ISSN_No;
void accept(){
cout<<”Enter journal name, price and ISSN number”;
cin>>journal_nm>>price>>ISSN_No;
}
};
void main(){
journal j1,j2;
clrscr();
j1.accept();
j2.accept();
if(j1.price>j2.price)
cout<<j1.journal_nm<<” has greater price ”<<j1.price;
else
cout<<j2.journal_nm<<” has greater price ”<<j2.price;
getch();
}
Prg 3-- wap to declare a class 'Day' having data members as
min. Accept min from user convert in appropriate hours
and sec. Display it for one object of a class.
#include<iostream.h>
#include<conio.h>
class day{
int min;
public:
void accept(){
cout<<”enter minute”;
cin>>min;
}
void display(){
cout<<”seconds=”<<min*60;
cout<<”minute=”<<min;
cout<<”hours=”<<min/60;
}};
void main(){
day d;
clrscr();
d.accept();
d.display();
getch();
}
Arrays
• Array in C++ is a group of similar types of elements that have
contiguous memory location.
• In C++, array index starts from 0.
• We can store only fixed set of elements in C++ array.

• Syntax:
• string cars[4];
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

• To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};


Array of Object
• Array of a Variables that are of type class are
called array of object.
Syntax:
classname objectname[size];
Example:
employee e[3];

student stud[20];
Mememory allocation for array
of a object
Prg.1—WAP to declare a class 'student' having data members
rollno and name. Accept and display this data for three
objects.
#include<iostream.h>
#include<conio.h>
class student{
int rollno;
char name[30];
public:
void get();
void put();
};
void student::get(){
cout<<”Enter rollno and name”;
cin>>rollno>>name;
}
void student::put(){
cout<<”Roll Number and name:”<<rollno<<name;
}
void main(){
student s[3];
for(int i=0;i<3;i++)
s[i].get();
for(int i=0;i<3;i++)
s[i].put();
getch();
}
Static data members
Following are the characteristics of static member
● It is initialized to zero when the first object of its class is
created. No other initialization is permitted
● Only one copy of that member is created for the entire
class and is shared by all the object of that class, no
matter how many objects are created.
● It is visible only within class, but its lifetime is the entire
program.
● Static variables are used to maintain values common to
the entire class.
●Each static variable must be defined outside the class
definition.
●Static data members are stored separately rather than as
a part of an object.
●Since they are associated with the class itself rather than
with any class object, they are also known as class variable.

Syntax:1)Inside the class:


static datatype variblename;
Eg:static int a;
2)outside the class:
return_type classname::variablename;
eg-int student::a;
int student::a=5;
Example:
#include<iostream.h>
#include<conio.h>
class item{
static int count;
public:
void DisplayCounter() {
count++;
cout<<"count:"<<count;
}
};
int item::count;
int main()
{
item a,b,c;
a.DisplayCounter();
b.DisplayCounter();
c.DisplayCounter();
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Static member function
● Like a static member variable we can also have static
member function. A member function declared with static
keyword is called as static member function. static
member function has following characteristics:
1.Static function can have access to only other static
members/functions declared in same class
2.Static member function can be called using class
name(instead of object) as
Class_name:: function_name;
Example:
#include <iostream.h>
#include <conio.h>
class test {
private:
static int count;
public:
void setCount();
static void DisplayCounter();
};
void test :: setCount(void)
{
count++;
}
void test :: DisplayCounter(void)
{
cout<<"Count:"<< count;
}
int test::count;
int main(void){
test t1, t2;
clrscr();
t1.setCount();
test :: DisplayCounter();
t2.setCount();
test :: DisplayCounter();
getch();
return(0);
}
Output: Count: 1
Count: 2
Friend Function
• A friend function is a function that is not a
member of a class but it can access private and
protected member of the class in which it is
declared as friend.

• Since friend function is not a member of class it


can not be accessed using object of the class.

• Sometimes it is required that private member of


the class can be accessed outside the class at
that time we have to use friend function.
A function can be declared as a friend by
preceding function declaration with friend
keyword as shown below:
friend Return_Type Function_Name (Argument
List);
Eg: friend void add();

Friend function can be called as foll


function_name(actual arguments);
• The function that is declared with the keyword
friend is known as friend function
• This function can be defined else where in the
program.
• The function definition does not use either keyword
friend or the scope operator::
• A function can be declared as a friend in any number
of classes.
• A friend function although not a member function,
has full access right to the private members of the
class
Friend function having following characteristics:
(1) A friend function can be declared inside class but it is not
member of the class.
(2) It can be declared either public or private without
affecting its meaning.
(3) A friend function is not a member of class so it is not
called using object of the class. It is called like normal
external function.
(4) A friend function accepts object as an argument to access
private or public member of the class.
(5) A friend function can be declared as friend in any number
of classes.
Example:
#include<iostream.h>
#include<conio.h>
class Circle {
int r;
public:
void input(){
cout<<"Enter Radius:";
cin>>r;
}
friend void area(Circle C);
};
void area(Circle C)
{
cout<<"Area of Circle is:"<<3.14*C.r*C.r;
}
void main()
{
Circle c1;
c1.input();
Area(c1);
getch();
}
Constructors in C++
• Constructor in C++ is a special method that
is invoked automatically at the time of object
creation.
• It is used to initialize the data members of new
objects generally.
• The constructor in C++ has the same name as
the class or structure.
• Constructor is invoked at the time of object
creation.
• It constructs the values i.e. provides data for
the object which is why it is known as
constructors.
• Constructor is a member function of a class,
whose name is same as the class name.
• Constructor is a special type of member
function that is used to initialize the data
members for an object of a class automatically,
when an object of the same class is created.
• Constructor is invoked at the time of object
creation. It constructs the values i.e. provides
data for the object that is why it is known as
constructor.
• Constructor do not return value, hence they do
not have a return type.
The<class-name>
prototype(list-of-parameters);
of the constructor looks like
• Constructor can be defined inside the class
declaration or outside the class declaration
a. Syntax for defining the constructor within the class

<class-name>(list-of-parameters)
{
//constructor definition
}
b. Syntax for defining the constructor outside the class

<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we create the
object of the class
s.display();
return 0;

}
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{ student s;
s.display();
return 0;
}
Characteristics of constructor
• The name of the constructor is same as its
class name.
• Constructors are mostly declared in the
public section of the class though it can be
declared in the private section of the class.
• Constructors do not return values; hence
they do not have a return type.
• A constructor gets called automatically when
we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
Types of constructor

1. Default Constructors: Default constructor is the constructor which


doesn’t take any argument. It has no parameters. It is also called a zero-
argument constructor.

#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;
}
Output a: 10
b: 20
2. Parameterized Constructors:
• It is possible to pass arguments to
constructors.
• Typically, 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.
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

return 0;
}
Output
p1.x = 10, p1.y = 15
Uses of Parameterized constructor:
• It is used to initialize the various data elements of
different objects with different values when they are
created.
• It is used to overload constructors.
Can we have more than one constructor in a
class?
Yes, It is called Constructor Overloading.

Note: when the parameterized constructor is defined


and no default constructor is defined explicitly, the
compiler will not implicitly call the default constructor
and hence creating a simple object as

Student s; //Will flash an error


3. Copy Constructor:
• A copy constructor is a member function that
initializes an object using another object of the
same class.
• Whenever we define one or more non-default
constructors( with parameters ) for a class, a
default constructor( without parameters )
should also be explicitly defined as the
compiler will not provide a default constructor
in this case.
• However, it is not necessary but it’s
considered to be the best practice to always
define a default constructor.
• Copy constructor takes a reference to an
object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
#include <iostream>
using namespace std;
class point {
private:
double x, y;
public:
// Non-default Constructor &
// default Constructor
point(double px, double py) { x = px, y = py; }
};
int main(void)
{
point b = point(5, 6); }
C++ Destructor
• A destructor works opposite to constructor; it
destructs the objects of classes.
• It can be defined only once in a class. Like
constructors, it is invoked automatically.
• A destructor is defined like constructor. It must
have same name as class. But it is prefixed
with a tilde sign (~).
• Note: C++ destructor cannot have parameters. Moreover,
modifiers can't be applied on destructors.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
Thank You !!!
(Construct Positivity…)

You might also like