0% found this document useful (0 votes)
16 views20 pages

Sample Programs Classes in C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views20 pages

Sample Programs Classes in C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Example 1: Object and Class in C++ Programming

// Program to illustrate the working of


// objects and class in C++ Programming
#include <iostream>
using namespace std;
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// assign values to data members
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
// calculate and display the area and volume of the room
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
Output:
Area of Room = 1309
Volume of Room = 25132.8
Example 2: Using public and private in C++ Class
// Program to illustrate the working of
// public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
Sample Output:
Area of Room = 1309
Volume of Room = 25132.8
C++ Constructors
A constructor is a special type of member function that is called automatically when an object is
created.
In C++, a constructor has the same name as that of the class and it does not have a return type. For
example,
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
• has the same name as the class,
• does not have a return type, and
• is public
C++ Default Constructor
A constructor with no parameters is known as a default constructor. In the example above, Wall() is a
default constructor.
Example 1: C++ Default Constructor
// C++ program to demonstrate the use of default constructor
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// default constructor to initialize variable
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};
int main() {
Wall wall1;
return 0;
}
Output:
Creating a wall.
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. This sets the length variable of
the object to 5.5.
Note: If we have not defined a constructor in our class, then the C++ compiler will automatically
create a default constructor with an empty code and no parameters.
C++ Parameterized Constructor
In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred
method to initialize member data.
// C++ program to calculate the area of a wall
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
Output:
Area of Wall 1: 90.3
Area of Wall 2: 53.55
Here, we have created a parameterized constructor Wall() that has 2 parameters: double len and
double hgt. The values contained in these parameters are used to initialize the member variables
length and height.
When we create an object of the Wall class, we pass the values for the member variables as
arguments. The code for this is:
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
With the member variables thus initialized, we can now calculate the area of the wall with the
calculateArea() function.
C++ Copy Constructor
The copy constructor in C++ is used to copy data of one object to another.
Example 3: C++ Copy Constructor
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}
// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
Output
Area of Wall 1: 90.3
Area of Wall 2: 90.3
In this program, we have used a copy constructor to copy the contents of one object of the Wall class

to another. The code of the copy constructor is:

Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

Notice that the parameter of this constructor has the address of an object of the Wall class.

We then assign the values of the variables of the obj object to the corresponding variables of the

object calling the copy constructor. This is how the contents of the object are copied.

In main(), we then create two objects wall1 and wall2 and then copy the contents of wall1 to wall2:

// copy contents of wall1 to wall2


Wall wall2 = wall1;

Here, the wall2 object calls its copy constructor by passing the address of the wall1 object as its

argument i.e. &obj = &wall1.

Note: A constructor is primarily used to initialize objects. They are also used to run a default code

when an object is created.

How to pass and return object from C++ Functions?

In C++ programming, we can pass objects to a function in a similar manner as passing regular

arguments.

Example 1: C++ Pass Objects to Function

// C++ program to calculate the average marks of two students

#include <iostream>
using namespace std;

class Student {

public:
double marks;
// constructor to initialize marks
Student(double m) {
marks = m;
}
};

// function that has objects as parameters


void calculateAverage(Student s1, Student s2) {

// calculate the average of marks of s1 and s2


double average = (s1.marks + s2.marks) / 2;

cout << "Average Marks = " << average << endl;

int main() {
Student student1(88.0), student2(56.0);

// pass the objects as arguments


calculateAverage(student1, student2);

return 0;
}
Run Code

Output

Average Marks = 72

Here, we have passed two Student objects student1 and student2 as arguments to
the calculateAverage() function.
Example 2: C++ Return Object from a Function

#include <iostream>
using namespace std;

class Student {
public:
double marks1, marks2;
};

// function that returns object of Student


Student createStudent() {
Student student;

// Initialize member variables of Student


student.marks1 = 96.5;
student.marks2 = 75.0;

// print member variables of Student


cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;

// Call function
student1 = createStudent();

return 0;
}
Run Code

Output

Marks1 = 96.5
Marks2 = 75
Return object from
function in C++

In this program, we have created a function createStudent() that returns an object of Student class.

We have called createStudent() from the main() method.

// Call function
student1 = createStudent();

Here, we are storing the object returned by the createStudent() method in the student1

C++ Operator Overloading

In this tutorial, we will learn about operator overloading with the help of examples.

In C++, we can change the way operators work for user-defined types like objects and structures. This

is known as operator overloading. For example,

Suppose we have created three objects c1, c2 and result from a class named Complex that represents

complex numbers.

Since operator overloading allows us to change how operators work, we can redefine how

the + operator works and use it to add the complex numbers of c1 and c2 by writing the following

code:

result = c1 + c2;

instead of something like


result = c1.addNumbers(c2);

This makes our code intuitive and easy to understand.

Note: We cannot use operator overloading for fundamental data types like int, float, char and so on.

Syntax for C++ Operator Overloading

To overload an operator, we use a special operator function. We define the function inside the class or

structure whose objects/variables we want the overloaded operator to work with.

class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};

Here,

• returnType is the return type of the function.

• operator is a keyword.

• symbol is the operator we want to overload. Like: +, <, -, ++, etc.

• arguments is the arguments passed to the function.

Operator Overloading in Unary Operators


Unary operators operate on only one operand. The increment operator ++ and decrement operator -

- are examples of unary operators.

Example1: ++ Operator (Unary Operator) Overloading

// Overload ++ when used as prefix

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:

// Constructor to initialize count to 5


Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++ () {
++value;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1;

// Call the "void operator ++ ()" function


++count1;

count1.display();
return 0;
}
Output

Count: 6

Here, when we use ++count1;, the void operator ++ () is called. This increases the value attribute for

the object count1 by 1.

Note: When we overload operators, we can use it to work in any way we like. For example, we could

have used ++ to increase value by 100.

However, this makes our code confusing and difficult to understand. It's our job as a programmer to

use operator overloading properly and in a consistent and intuitive way.

The above example works only when ++ is used as a prefix. To make ++ work as a postfix we use this

syntax.

void operator ++ (int) {


// code
}

Notice the int inside the parentheses. It's the syntax used for using unary operators as postfix; it's not a

function parameter.

Example 2: ++ Operator (Unary Operator) Overloading

// Overload ++ when used as prefix and postfix

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:
// Constructor to initialize count to 5
Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++ () {
++value;
}

// Overload ++ when used as postfix


void operator ++ (int) {
value++;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1;

// Call the "void operator ++ (int)" function


count1++;
count1.display();

// Call the "void operator ++ ()" function


++count1;

count1.display();
return 0;
}
Run Code

Output

Count: 6
Count: 7
The Example 2 works when ++ is used as both prefix and postfix. However, it doesn't work if we try

to do something like this:

Count count1, result;

// Error
result = ++count1;

This is because the return type of our operator function is void. We can solve this problem by

making Count as the return type of the operator function.

// return Count when ++ used as prefix

Count operator ++ () {
// code
}

// return Count when ++ used as postfix

Count operator ++ (int) {


// code
}

Example 3: Return Value from Operator Function (++ Operator)

#include <iostream>
using namespace std;

class Count {
private:
int value;

public
:
// Constructor to initialize count to 5
Count() : value(5) {}

// Overload ++ when used as prefix


Count operator ++ () {
Count temp;
// Here, value is the value attribute of the calling object
temp.value = ++value;

return temp;
}

// Overload ++ when used as postfix


Count operator ++ (int) {
Count temp;

// Here, value is the value attribute of the calling object


temp.value = value++;

return temp;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1, result;

// Call the "Count operator ++ ()" function


result = ++count1;
result.display();

// Call the "Count operator ++ (int)" function


result = count1++;
result.display();

return 0;
}
Run Code

Output

Count: 6
Count: 6

Here, we have used the following code for prefix operator overloading:

// Overload ++ when used as prefix


Count operator ++ () {
Count temp;

// Here, value is the value attribute of the calling object


temp.value = ++value;

return temp;
}

The code for the postfix operator overloading is also similar. Notice that we have created an

object temp and returned its value to the operator function.

Also, notice the code

temp.value = ++value;

The variable value belongs to the count1 object in main() because count1 is calling the function,

while temp.value belongs to the temp object.

Operator Overloading in Binary Operators

Binary operators work on two operands. For example,

result = num + 9;

Here, + is a binary operator that works on the operands num and 9.

When we overload the binary operator for user-defined types by using the code:

obj3 = obj1 + obj2;

The operator function is called using the obj1 object and obj2 is passed as an argument to the

function.
Example 4: C++ Binary Operator Overloading

// C++ program to overload the binary operator +


// This program adds two complex numbers

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}

void input() {
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}

// Overload the + operator


Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}

void output() {
if (imag < 0)
cout << "Output Complex number: " << real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};

int main() {
Complex complex1, complex2, result;

cout << "Enter first complex number:\n";


complex1.input();

cout << "Enter second complex number:\n";


complex2.input();

// complex1 calls the operator function


// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();

return 0;
}
Run Code

Output

Enter first complex number:


Enter real and imaginary parts respectively: 9 5
Enter second complex number:
Enter real and imaginary parts respectively: 7 6
Output Complex number: 16+11i

In this program, the operator function is:

Complex operator + (const Complex& obj) {


// code
}

Instead of this, we also could have written this function like:

Complex operator + (Complex obj) {


// code
}

However,

• using & makes our code efficient by referencing the complex2 object instead of making a

duplicate object inside the operator function.

• using const is considered a good practice because it prevents the operator function from

modifying complex2.
Overloading binary
operators in C++

Things to Remember in C++ Operator Overloading

1. Two operators = and & are already overloaded by default in C++. For example, to copy

objects of the same class, we can directly use the = operator. We do not need to create an

operator function.

2. Operator overloading cannot change the precedence and associativity of operators. However,

if we want to change the order of evaluation, parentheses should be used.

3. There are 4 operators that cannot be overloaded in C++. They are:

a. :: (scope resolution)

b. . (member selection)

c. .* (member selection through pointer to function)

d. ?: (ternary operator)

You might also like