UNIT-2 Classes, Constructors, and Overloading 9+6
HOU
RS
Defining classes and objects, object construction & destruction-Types of constructors: default,
parameterized, dynamic, copy constructor, and destructors-Operator overloading (unary,
binary, assignment, new/delete) and type conversion techniques-friend functions,
implicit/explicit constructors.
🔶 1. DEFINING CLASSES AND OBJECTS
📌 What is a Class?
A class is a user-defined datatype that combines data (variables) and functions (methods) into
a single unit.
Classes implement OOP principles: abstraction, encapsulation, inheritance, and
polymorphism.
Internally:
● Stored in memory only when objects are created.
● Blueprint only defines the structure, not memory.
📌 What is an Object?
An object is an instance of a class.
It occupies memory and allows access to class members.
📌 Class Anatomy
A class contains:
1. Data members (attributes)
2. Member functions (methods)
3. Access specifiers (public, private, protected)
Programming in C++/ Prepared by B Kalpana -HOD CSE 1
4. Constructors
5. Destructors
6. Static members
7. Friend functions (optional)
📌 Access Specifiers
Specifier Meaning Accessibility
public Accessible Code outside class can use it
everywhere
private Hidden from outside Only member functions can
access
protecte Hidden but inherited Base → derived class can access
d
📌 Simple but deep example
#include <iostream>
using namespace std;
class Student {
private:
int roll;
string name;
public:
void setData(int r, string n) {
roll = r;
name = n;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
Programming in C++/ Prepared by B Kalpana -HOD CSE 2
int main() {
Student s1, s2; // objects
[Link](1, "Rahul");
[Link](2, "Priya");
[Link]();
[Link]();
}
🔶 2. OBJECT CONSTRUCTION & DESTRUCTION
When an object is created → constructor runs
When object ends its lifetime → destructor runs
🔵 CONSTRUCTORS (DETAILED)
📌 Definition
A constructor is a special method that initializes the data of an object automatically.
📌 Constructor Properties
● Same name as class
● No return type
● Automatically called
● Can be overloaded
● Can be private (Singleton pattern)
● Used for dynamic memory allocation, initialization
🟢 Types of Constructors (DETAILED)
Programming in C++/ Prepared by B Kalpana -HOD CSE 3
1️⃣ Default Constructor
● No arguments
● Compiler provides one if you don’t define it
● Initializes values to garbage unless you set them
Example:
class A {
public:
A() {
cout << "Default constructor called\n";
}
};
2️⃣ Parameterized Constructor
● Takes arguments
● Allows initializing with different values
class Rectangle {
public:
int l, b;
Rectangle(int x, int y) { l = x; b = y; }
};
3️⃣ Copy Constructor
● Creates a new object as a copy of an existing object
Compiler-generated Copy Constructor:
Copies values member-wise, shallow copy.
Programming in C++/ Prepared by B Kalpana -HOD CSE 4
Example (User-defined):
class Sample {
public:
int x;
Sample(int a) { x = a; }
Sample(const Sample &s) {
x = s.x;
}
};
4️⃣ Dynamic Constructor
● Uses new inside constructor
● Allocates memory dynamically (heap)
class Name {
char *str;
public:
Name(const char *s) {
str = new char[strlen(s)+1];
strcpy(str, s);
}
};
5️⃣ Destructor (Deep Explanation)
🧨 Definition:
Destructor releases resources (memory/files).
It begins with ~classname()
Properties:
● No return type
● No parameters
Programming in C++/ Prepared by B Kalpana -HOD CSE 5
● Automatically invoked at object end
● Only one allowed
Example:
~Name() {
delete[] str;
}
🔶 3. OPERATOR OVERLOADING (DETAILED)
📌 What is operator overloading?
You redefine operators so they work with objects.
📌 Why needed?
To support operations like:
c3 = c1 + c2; // Complex numbers
m1 > m2; // Compare objects
📌 Operators that CANNOT be overloaded:
● . (dot)
● :: (scope resolution)
● ?: (ternary)
● sizeof
● .* (pointer to member)
🟢 Unary Operator Overloading
Programming in C++/ Prepared by B Kalpana -HOD CSE 6
Example: Overload ++ for object
class Num {
public:
int x;
Num(int a) { x = a; }
void operator++() { // prefix ++
x = x + 1;
}
};
🟢 Binary Operator Overloading
class Complex {
public:
int r, i;
Complex(int a, int b) { r=a; i=b; }
Complex operator + (Complex c) {
return Complex(r + c.r, i + c.i);
}
};
🟢 Assignment Operator Overloading (=)
Used when assigning one object to another.
Demo& operator=(const Demo &d) {
value = [Link];
return *this;
}
🟢 new and delete Operator Overloading
You can control how memory is allocated/deallocated for your class.
void* operator new(size_t size) {
return malloc(size);
Programming in C++/ Prepared by B Kalpana -HOD CSE 7
}
void operator delete(void* p) {
free(p);
}
🔶 4. TYPE CONVERSION (VERY IMPORTANT)
📌 Types:
1. Basic → Class
2. Class → Basic
3. Class → Class
1️⃣ Basic to Class
Using parameterized constructor:
Time t = 5; // int to object
2️⃣ Class to Basic
Using cast operator:
operator int() {
return hours;
}
3️⃣ Class to Class
operator DestinationClass() {
DestinationClass temp(...);
return temp;
}
Programming in C++/ Prepared by B Kalpana -HOD CSE 8
🔶 5. FRIEND FUNCTION (Deep)
📌 Definition:
A friend function is not a member of the class but can access its private/protected members.
Why?
● Useful for operator overloading
● Useful for two classes sharing info
Example:
class A {
int x;
public:
friend void show(A);
};
🔶 6. IMPLICIT AND EXPLICIT CONSTRUCTORS
✔ Implicit Constructor Call
Compiler automatically uses constructor:
Demo d = 10; // implicit conversion allowed
✔ Explicit Constructor
Stops accidental conversions.
explicit Demo(int x) { }
Now this is NOT allowed:
Programming in C++/ Prepared by B Kalpana -HOD CSE 9
Demo d = 10; // error
REVISION PROGRAMS
⭐ 1. Defining Classes and Objects
✅ Program 1
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << "\nAge: " << age << endl;
}
};
int main() {
Student s1;
[Link] = "Rahul";
[Link] = 20;
[Link]();
}
Output:
Name: Rahul
Age: 20
✅ Program 2
#include <iostream>
using namespace std;
class Car {
public:
string brand;
Programming in C++/ Prepared by B Kalpana -HOD CSE 10
int year;
void show() {
cout << brand << " - " << year << endl;
}
};
int main() {
Car c;
[Link] = "Toyota";
[Link] = 2020;
[Link]();
}
Output:
Toyota - 2020
⭐ 2. Constructors (All Types)
🔹 (A) Default Constructor
Program 1
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "Default Constructor Called" << endl;
}
};
int main() {
A obj;
}
Output:
Programming in C++/ Prepared by B Kalpana -HOD CSE 11
Default Constructor Called
Program 2
#include <iostream>
using namespace std;
class Box {
public:
int length;
Box() {
length = 10;
cout << "Length = " << length << endl;
}
};
int main() {
Box b;
}
Output:
Length = 10
🔹 (B) Parameterized Constructor
Program 1
#include <iostream>
using namespace std;
class Add {
public:
int a, b;
Add(int x, int y) {
a = x; b = y;
cout << "Sum = " << a + b << endl;
}
};
Programming in C++/ Prepared by B Kalpana -HOD CSE 12
int main() {
Add obj(5, 6);
}
Output:
Sum = 11
Program 2
#include <iostream>
using namespace std;
class Student {
public:
string name;
Student(string n) {
name = n;
cout << "Student: " << name << endl;
}
};
int main() {
Student s("Kannan");
}
Output:
Student: Kannan
🔹 (C) Dynamic Constructor (using new)
Program 1
#include <iostream>
using namespace std;
class Sample {
public:
int *p;
Programming in C++/ Prepared by B Kalpana -HOD CSE 13
Sample(int x) {
p = new int;
*p = x;
cout << "Value = " << *p << endl;
}
};
int main() {
Sample s(50);
}
Output:
Value = 50
Program 2
#include <iostream>
using namespace std;
class Array {
public:
int *arr;
Array(int size) {
arr = new int[size];
cout << "Array of size " << size << " created" << endl;
}
};
int main() {
Array a(5);
}
Output:
Array of size 5 created
🔹 (D) Copy Constructor
Programming in C++/ Prepared by B Kalpana -HOD CSE 14
Program 1
#include <iostream>
using namespace std;
class Demo {
public:
int a;
Demo(int x) { a = x; }
Demo(Demo &obj) { a = obj.a; }
};
int main() {
Demo d1(10);
Demo d2(d1);
cout << d2.a;
}
Output:
10
Program 2
#include <iostream>
using namespace std;
class Student {
public:
string name;
Student(string n) { name = n; }
Student(Student &s) { name = [Link]; }
};
int main() {
Student s1("Vijay");
Student s2(s1);
cout << [Link];
}
Output:
Vijay
Programming in C++/ Prepared by B Kalpana -HOD CSE 15
⭐ 3. Destructor
Program 1
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Object Created" << endl; }
~Test() { cout << "Object Destroyed" << endl; }
};
int main() {
Test t;
}
Output:
Object Created
Object Destroyed
Program 2
#include <iostream>
using namespace std;
class Demo {
public:
int *p;
Demo() {
p = new int(5);
cout << "Memory allocated" << endl;
}
~Demo() {
delete p;
cout << "Memory freed" << endl;
}
};
Programming in C++/ Prepared by B Kalpana -HOD CSE 16
int main() {
Demo d;
}
Output:
Memory allocated
Memory freed
⭐ 4. Operator Overloading
🔹 Unary Operator Overloading
Program 1
#include <iostream>
using namespace std;
class A {
public:
int x;
A(int a){ x = a; }
void operator++() { x++; }
};
int main() {
A obj(5);
++obj;
cout << obj.x;
}
Output:
6
Program 2
Programming in C++/ Prepared by B Kalpana -HOD CSE 17
#include <iostream>
using namespace std;
class B {
public:
int n;
B(int x){ n = x; }
void operator--(){ n--; }
};
int main(){
B b(10);
--b;
cout << b.n;
}
Output:
9
🔹 Binary Operator Overloading
Program 1 (Add Objects)
#include <iostream>
using namespace std;
class A {
public:
int x;
A(int a){ x = a; }
A operator+(A obj) {
return A(x + obj.x);
}
};
int main() {
A a1(5), a2(10), a3(0);
a3 = a1 + a2;
cout << a3.x;
}
Programming in C++/ Prepared by B Kalpana -HOD CSE 18
Output:
15
Program 2
#include <iostream>
using namespace std;
class Num {
public:
int n;
Num(int x){ n = x; }
Num operator*(Num obj){
return Num(n * obj.n);
}
};
int main(){
Num a(4), b(3), c(0);
c = a * b;
cout << c.n;
}
Output:
12
🔹 Assignment Operator Overloading
Program 1
#include <iostream>
using namespace std;
class Demo {
public:
int a;
Programming in C++/ Prepared by B Kalpana -HOD CSE 19
Demo(int x){ a = x; }
Demo operator=(Demo &obj) {
a = obj.a;
return *this;
}
};
int main(){
Demo d1(10), d2(0);
d2 = d1;
cout << d2.a;
}
Output:
10
Program 2
#include <iostream>
using namespace std;
class Person {
public:
string name;
Person(string n){ name = n; }
Person operator=(Person &p){
name = [Link];
return *this;
}
};
int main(){
Person p1("Arun"), p2("None");
p2 = p1;
cout << [Link];
}
Output:
Programming in C++/ Prepared by B Kalpana -HOD CSE 20
Arun
🔹 new / delete Operator Overloading
(Overloading new/delete is advanced, but here are simple examples)
Program 1
#include <iostream>
using namespace std;
class Test {
public:
void* operator new(size_t size) {
cout << "Custom new called" << endl;
return malloc(size);
}
void operator delete(void* ptr) {
cout << "Custom delete called" << endl;
free(ptr);
}
};
int main(){
Test* t = new Test();
delete t;
}
Output:
Custom new called
Custom delete called
Program 2
#include <iostream>
using namespace std;
class Sample {
Programming in C++/ Prepared by B Kalpana -HOD CSE 21
public:
int x;
Sample() { x = 5; }
void* operator new(size_t size){
cout << "New operator overloaded" << endl;
return ::operator new(size);
}
void operator delete(void* p){
cout << "Delete operator overloaded" << endl;
::operator delete(p);
}
};
int main(){
Sample* s = new Sample();
delete s;
}
Output:
New operator overloaded
Delete operator overloaded
⭐ 5. Type Conversion Techniques
(A) Class to Basic
Program 1
#include <iostream>
using namespace std;
class A {
int x;
public:
A(int a){ x = a; }
operator int() { return x; }
Programming in C++/ Prepared by B Kalpana -HOD CSE 22
};
int main() {
A obj(20);
int n = obj;
cout << n;
}
Output:
20
(B) Basic to Class
Program 2
#include <iostream>
using namespace std;
class B {
public:
int val;
B(int x){ val = x; }
};
int main(){
int n = 30;
B obj(n);
cout << [Link];
}
Output:
30
⭐ 6. Friend Function
Program 1
Programming in C++/ Prepared by B Kalpana -HOD CSE 23
#include <iostream>
using namespace std;
class A {
private:
int x;
public:
A(){ x = 10; }
friend void show(A);
};
void show(A obj){
cout << obj.x;
}
int main(){
A a;
show(a);
}
Output:
10
Program 2
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box(){ length = 15; }
friend int getLength(Box);
};
int getLength(Box b){
return [Link];
}
int main(){
Programming in C++/ Prepared by B Kalpana -HOD CSE 24
Box b;
cout << getLength(b);
}
Output:
15
⭐ 7. Implicit & Explicit Constructors
Program 1 — Implicit
#include <iostream>
using namespace std;
class A {
public:
int x;
A(int a){ x = a; } // implicit allowed
};
int main(){
A obj = 10; // implicit conversion
cout << obj.x;
}
Output:
10
Program 2 — Explicit
#include <iostream>
using namespace std;
class B {
public:
int x;
explicit B(int a){ x = a; }
Programming in C++/ Prepared by B Kalpana -HOD CSE 25
};
int main(){
B obj(20); // OK
cout << obj.x;
}
Output:
20
Programming in C++/ Prepared by B Kalpana -HOD CSE 26