1.
Introduction to Objects and Classes
Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and
brake.
Attributes and methods are basically variables and functions that belongs to the class. These are often referred
to as "class members".
→Classes in C++
In C++, a class is a user-defined data type that groups data members (variables) and member functions
(methods) into a single unit. It’s one of the core concepts of Object-Oriented Programming (OOP).
The class members that have been declared as private Can be assed only from with in the class. The public
members can be accesed from outside the class .The variable declare inside the class are called Data
members. And the function are known as member function.
Basic Syntax of a Class:
class ClassName {
private:
// data members (variables)
public:
// member functions (methods)
};
Example:
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
→Objects in C++
An object is a runtime entity created from a class, used to access and manipulate the properties and behaviors
defined in that class.
Basic Object Syntax
ClassName objectName;
We have already created the class named MyClass, so now we can use this to create [Link] create an
object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example:
Create an object called "myObj" and access the attributes:
#include <iostream.h>
#include <conio.h>
class MyClass
{
public:
int myNum;
string myString;
};
int main() {
MyClass myObj; // Create an object of MyClass
[Link] = 15;
[Link] = "any text ";
cout << [Link] << "\n";
cout << [Link];
return 0;
}
[Link] class in C++
Class declaration in C++ is the process of defining a class by specifying its name, data members, and member
functions without creating any objects.
•Declaration starts with the keyword class
•Followed by class name
•Ends with a semicolon (;)
-Contains:
•Data members (variables)
•Member functions (methods)
•Uses access specifiers (private, public, protected)
Syntax of Class Declaration:
class ClassName {
private:
// data members
public:
// member functions
};
Example Program :
#include <iostream>
#include <conio.h>
class Student {
private:
int rollNo;
string name;
public:
void setData(int r, string n) {
rollNo = r;
name = n;
}
void display() {
cout << "Roll Number: " << rollNo << endl;
cout << "Name: " << name << endl;
}
};
int main() {
Student s1; // Creating object
[Link](101, "Ali");
[Link]();
return 0;
}
Output : Roll Number: 101
Name: Ali
[Link] OF FUNCTION
A C++ function consists of two main parts: the function declaration (or prototype) and the function definition.
The function definition itself is further broken down into specific components.
→In C++, a function definition provides the actual body of the function, which contains the block of code that
specifies what the function does when it is called.
→In C++, the function declaration (also known as a function prototype) informs the compiler about a function's
name, return type, and parameters.
•Prototype in C++
A function prototype in C++ is a declaration that informs the compiler about the function's existence, its name,
return type, and the number and type of its parameters before the function is actually defined.
Syntax :
The syntax for a function prototype is similar to the function's header, but it ends with a semicolon and does not
include the function body
return_type function_name(parameter_list);
Example : int add(int, int);
• FUNCTION CALL IN C++
Declared functions are not executed immediately. They are "saved for later use", and will be executed later,
when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
Example:
Inside main, call myFunction():
#include <iostream>
#include <conio.h>
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
Output: I just got executed!
A function can be called multiple times
•PARAMETERS IN C++
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as
you want, just separate them with a comma(,).
Syntax :
return_type function_name(data_type param1, data_type param2, ...);
Example :
int add(int a, int b); // a and b are parameters
•PASSING ARGUMENTS IN C++
In C++, an argument is the actual value or variable that is passed to a function when it is called. Arguments
provide the input data that a function needs to perform its task.
Basic Syntax :
function_name(value1, value2, ...);
The values passed inside the parentheses are called arguments.
Example : add(5, 3);
→Example program for both concepts
#include <iostream.h>
#include <string.h>
#include <conio.h>
void myFunction(string fname)
{
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a
parameter, while Liam, Jenny and Anja are arguments.
# TWO TYPES OF PASSING ARGUMENTS:
•CALL BY VALUE
•CALL BY REFERENCE
→CALL BY VALUE
In C++, call by value is a method of passing arguments to a function where a copy of the actual data is given to
the function's formal parameters. Any modifications made to these parameters inside the function do not affect
the original variable in the caller's scope.
Syntax :
return_type function_name(data_type parameter) {
// function body
}
function_name(argument);
Example :
#include <iostream.h>
#include <conio.h>
void change(int x) // parameter
{
x = 20;
cout << "Inside function: " << x << endl;
}
int main() {
int a = 10;
change(a); // passing argument
cout << "Outside function: " << a << endl;
return 0;
}
Output :
Inside function: 20
Outside function: 10
→CALL BY REFFERENCE
In call by reference, the actual variable itself is passed to the function using references.
So, any changes made inside the function affect the original variable.
Syntax:
return_type function_name(data_type ¶meter) {
// function body
}
function_name(variable);
Example:
#include <iostream.h>
#include <conio.h>
void change(int &x) // reference parameter
{
x = 20;
cout << "Inside function: " << x << endl;
}
int main() {
int a = 10;
change(a); // passing argument
cout << "Outside function: " << a << endl;
return 0;
}
Output
Inside function: 20
Outside function: 20
•TYPES OF FUNCTIONS
There are four type:
1. A function with no argument and no return value.
2. A function with argument but no return value.
3. A function with no argument but returns a value.
4. A function with arguments and return value.
(i) A FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE
A function with no arguments and no return value is defined as a block of code that performs a specific task
without receiving input from the caller and without sending any result back.
The function is called with empty parentheses, e.g., function_name();. It does not receive any values or data
from the calling function.
Syntax :
void function_name(void)
{
// statements
}
-void (before name) → no return value
-(void) → no arguments
Example:
#include <iostream>
#include<conio.h>
void greet() {
cout << "Hello, welcome to C++!" << endl;
}
int main() {
greet();
return 0;
}
Output : Hello, welcome to C++!
(ii)A FUNCTION WITH ARGUMENTS BUT NO RETURN VALUE
A function with arguments but no return value is a function that accepts input values (arguments) from the
calling function, performs a specific task, but does not return any value back.
Such functions are declared using the void return type.
Syntax :
void function_name(data_type parameter1, data_type parameter2, ...)
{
// statements
}
-void (before name) → no return value
-(parameter list) → with argument
Example :
#include <iostream.h>
#include <conio.h>
void multiply(int a, int b)
{
int result = a * b;
cout << "Product = " << result;
}
int main()
{
multiply(4, 5);
return 0;
}
Output : Product = 20
(iii)A FUNCTION WITH NO ARGUMENTS BUT RETURN VALUE
A function with no arguments but returns a value is a function that does not take any input from the calling
function, but returns a value after performing some operation.
Syntax :
return_type function_name()
{
// statements
return value;
}
-Return type (before name) → with return value
-(Void) → no argument
Example :
#include <iostream.h>
#include <conio.h>
int getNumber()
{
int num = 10;
return num;
}
int main()
{
int result;
result = getNumber();
cout << "Number = " << result;
return 0;
}
Output : Number = 10
(iv) A FUNCTION WITH ARGUMENTS AND RETURN VALUE
A function with arguments and return value is a function that accepts input values (arguments) from the calling
function, performs some operation, and returns a result back to the calling function.
Syntax :
return_type function_name(data_type parameter1, data_type parameter2, ...)
{
// statements
return value;
}
-Return type (before name)→ with return value
-(Parameter list) →with arguments
Example :
#include <iostream.h>
#include <conio.h>
int add(int a, int b)
{
int sum = a + b;
return sum;
}
int main()
{
int result;
result = add(5, 3);
cout << "Sum = " << result;
return 0;
}
Output : Sum = 8
•INLINE FUNCTION
An inline function in C++ is a function for which the compiler is requested to substitute the function's body
directly at each point where it is called during compilation
Syntax :
inline function _header
{
function body
}
Example :
#include <iostream.h>
#include <conio.h>
inline int getSum(int a, int b){
return a + b;
}
int main(){
int num1 = 5, num2 = 10;
int result = getSum(num1, num2);
cout << "Sum: " << result << endl;
return 0;
}
Output: sum: 15
[Link] objects
In C++, creating an object means instantiating a class, allocating memory for its data members, and initializing
them using a constructor. The object has its own set of attributes (data) and methods (functions).
Syntax:
ClassName objectName(parameters);
Example program:
#include <iostream.h>
#include <conio.h>
class Student {
public:
string name;
int age;
Student(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Student student1("John", 20); // Create an object
[Link]();
return 0;
}
Output:
Name: John
Age: 20
•Polymorphism
Polymorphism in C++ is a core concept of object-oriented programming that allows a single function, operator,
or object to behave in multiple ways depending on the context.
This feature enhances code reusability, flexibility, and maintainability by allowing developers to create a single
interface that can be used for a variety of different data types or classes.
Example :
#include <iostream.h>
#include<conio.h>
int add(int a, int b) // Function to add two integers
{
return a + b;
}
int add(int a, int b, int c) // Function to add three integers (same name, different parameters)
{
return a + b + c;
}
int main() {
cout << add(10, 20) << endl; //Calls the first add() function
cout << add(10, 20, 30) << endl; // Calls the second add() function
return 0;
}
Output:
30
60
◦The ability of one function name (add) to perform different tasks depending on the input parameters.
◦This program demonstrates compile-time polymorphism (also called static polymorphism) because the
decision of which function to call is made during compilation.
→There are two types of polymorphism:
1. Compile time polymorphism.
2. Run time polymorphism.
1. Compile time polymorphism..
Compile-time polymorphism, also known as static polymorphism or early binding, is a mechanism in C++ where
the function call is resolved by the compiler during the compilation phase, before the program runs.
Compile time polymorphism are of two type :
a. Function overloading
b. Operator overloading
→Function overloading
Function overloading in C++ is a feature that allows a programmer to define multiple functions with the same
name within the same scope, provided they have different parameter lists.
Syntax:
return_type function_name(parameter_list1) {
// function body 1
}
return_type function_name(parameter_list2) {
// function body 2
}
......
Example:
#include <iostream.h>
# include <conio.h>
class Demo {
public:
void show(int a) {
cout << "Integer: " << a << endl;
}
void show(double b) {
cout << "Double: " << b << endl;
}
};
int main() {
Demo d;
[Link](10);
[Link](5.5);
}
Output : Integer: 10
Double: 5.5
→Operator overloading
Redefining the way an operator (like +, -, *, <<, >>) works for user-defined data types (classes or structs). The
compiler selects the correct implementation based on the operand types involved.
Syntax:
Return type classnane:: operator op(argument list)
{
// function body
}
Example :
#include <iostream.h>
#include <conio.h>
class Test {
public:
int x;
Test(int i) {
x = i;
}
Test operator+(Test t) {
return Test(x + t.x);
}
};
int main() {
Test t1(5), t2(10);
Test t3 = t1 + t2;
cout << t3.x;
}
Output: 15
2. Runtime Polymorphism (Dynamic Binding / Late Binding)
Also known as dynamic polymorphism or late binding, in this type, the function call is resolved during the
program's execution, not at compile time. This allows for greater flexibility, as the appropriate function
implementation is determined by the actual object type at runtime.
Example :
#include <iostream.h>
#include <conio.h>
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* a; // base class pointer
Dog d;
a = &d; // base pointer points to derived object
a->sound(); // calls Dog's sound()
return 0;
}
Output :Dog barks
Runtime polymorphism allows a base class pointer to call a derived class method at runtime using virtual
functions.
So even though the pointer is of type Animal, it executes the Dog’s sound() method.
Access Specifiers or Visibility Labels
Access specifiers control how the members (attributes and methods) of a class can be [Link] help
protect data and organize code so that only the right parts can be seen or changed.
There are three types of access specifiers:
•Public
•Private
•Protected
→Public Keyword
This can be used to allow object to access the member variables of class directly.
The member variables and functions declared followed by the keyword public and it is written inside the class
and terminated coln.
Syntax : public:
Example:
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Student s1;
[Link] = "Ali"; //Accessing public members directly
[Link] = 20;
[Link]();
return 0;
}
Output : Name: Ali
Age: 20
→Private Keyword
The private keyword in C++ is an access specifier used to declare class members (variables and functions)
that are only accessible within that same class. This is a core feature of object-oriented programming (OOP)
for data hiding and encapsulation.
Syntax : private :
Example :
#include <iostream>
using namespace std;
class Student {
private:
int age; // private data member
public:
void setAge(int a) { // public function to set value
age = a;
}
void display() { // public function to display value
cout << "Age: " << age << endl;
}
};
int main() {
Student s1;
// [Link] = 20; ❌ Not allowed (private member)
[Link](20); // accessing through public function
[Link]();
return 0;
}
Output : Age: 20
→Protected Keyword
The protected keyword in C++ is an access specifier that allows class members to be accessed within the
same class and its derived classes, but not from outside the class.
Syntax: protected:
Example :
#include <iostream>
using namespace std;
class Base {
protected:
int x = 5;
};
class Derived : public Base {
public:
void show() {
cout << x; // accessible here
}
};
int main() {
Derived d;
[Link]();
return 0;
Output: 5
Array of Objects
An array of objects is a data structure where each element in the array is an object (a collection of key–value
pairs). It’s commonly used to store multiple related records, like a list of users, products, or students.
Syntax : ClassName arrayName[size];
Example :
#include <iostream.h>
#include <conio.h>
class Student {
public:
int id;
char name[20];
void getData() {
cout << "Enter ID: ";
cin >> id;
cout << "Enter Name: ";
cin >> name;
}
void display() {
cout << "ID: " << id << " Name: " << name << endl;
}
};
void main() {
Student s[2]; // array of 2 objects
for(int i = 0; i < 2; i++) {
cout << "\nStudent " << i+1 << endl;
s[i].getData();
}
Output :
Student 1
Enter ID: 1
Enter Name: Ram
Student 2
Enter ID: 2
Enter Name: Sam
Details:
ID: 1 Name: Ram
ID: 2 Name: Sam
•Member function of a class as friends of another class in Cpp
A member function of one class can be declared as a friend of another class.
This allows that specific function to access private and protected members of the other class.
Syntax:
class B; // Forward declaration
class A {
public:
void show(B); // member function
};
class B {
private:
int data;
public:
B() { data = 10; }
friend void A::show(B); // A's function is friend of B
};
Example :
#include <iostream.h>
#include <conio.h>
class B; // forward declaration
class A {
public:
void display(B b); // member function
};
class B {
private:
int num;
public:
B() {
num = 50;
}
friend void A::display(B); // friend member function
};
void A::display(B b) {
cout << "Value of num: " << [Link];
}
void main() {
A objA;
B objB;
[Link](objB);
getch();
}
Output : Value of num: 50
→Accessing class members
Accessing class members means using the variables (data members) and functions (member functions) of a
class through an object of that class.
syntax: Objectname. function name ( actual_arg);
Example :
#include <iostream.h>
#include <conio.h>
class Test {
public:
void show(int x) { // function with parameter
cout << x;
}
};
void main() {
Test t;
[Link](5); // [Link](actual_arg)
getch();
}
Output :5
→Nesting of member function
In C++, the "nesting of member functions" is a common programming practice where one member function is called from
within another member function of the same class.
Example :
#include <iostream.h>
#include <conio.h>
class Test {
int num;
public:
void getData() {
num = 5;
}
void showData() {
getData(); // nested function call
cout << "Value: " << num;
}
};
void main() {
Test t;
[Link](); // calling only one function
getch();
}
•FRIEND CLASSES
A friend class in C++ is a class that is given permission to access the private and protected members of another
class.
This is done using the keyword friend inside the class whose members are being shared.
Syntax:
class ClassA {
friend class ClassB; // ClassB is friend of ClassA
};
Example :
#include <iostream.h>
#include <conio.h>
class A {
private:
int num = 10;
friend class B; // Declaring B as friend
};
class B {
public:
void display(A a) {
cout << "Value of num: " << [Link]; // Accessing private member
}
};
int main() {
A objA;
B objB;
[Link](objA);
return 0;
}
Output:Value of num: 10
→FRIEND FUNCTIONS
The private members of the class are accessed only from member function of the same [Link] non-member functions
cannot access the private data of the class.
Here, this mechanism allows a non-member function as access permission to the private member of the class. This can
be done by declaring a non-member function friend to the class whose private data to be accessed.
Here, friend is a keyword.
The function can be declared as friend function in one or more classes. The declaration of friend function is done inside
the class as private or public, and a function can be declared as friend function in any number of classes.
Syntax:
Class ABC
{
--------
--------
Public:
--------
friend void xyz (void) ;
};
Example :
#include <iostream.h>
#include <conio.h>
class Numbers {
private:
int a, b;
public:
void getData() {
cout << "Enter two numbers: ";
cin >> a >> b;
}
friend float mean(Numbers n); // Friend function
};
float mean(Numbers n) {
return (n.a + n.b) / 2.0;
}
void main() {
clrscr();
Numbers obj;
[Link]();
cout << "Mean value = " << mean(obj);
getch();
}
Output :
Enter two numbers: 10 20
Mean value = 15
[Link]
Constructor in C++: Constructor is a special member function whose task is to initialize the object of its class.
It is special because its name is same as that of class name. The constructor is invoked whenever an object of
its associated class is created.
They should be declared in public section and are invoked automatically when the objects are created. They do
not have a return type and cannot be inherited.
There are three types of constructors in C++ :
•Default Constructor
•Parameterized Constructor
•Copy Constructor
→Default Constructor
This constructor takes no arguments (or has all parameters with default values) and is used to create an object
with default initial values. If no constructors are explicitly defined in a class, the compiler automatically
generates a default [Link]
Syntax :
class ClassName {
public:
ClassName() {
// initialization code
}
};
Example :
#include <iostream.h>
#include <conio.h>
class Demo {
public:
int x;
// Default constructor
Demo() {
x = 10;
}
};
int main() {
Demo d1; // Default constructor is called automatically
cout << d1.x;
return 0;
}
Ouput :10
→Parameterized Constructor
This constructor allows you to pass arguments during object creation to initialize its data members with specific,
custom values. This adds flexibility to the initialization process.
Syntax :
class ClassName {
public:
ClassName(type1 arg1, type2 arg2, ...) {
// initialization using arguments
}
};
Example :
#include <iostream.h>
#include <stdio.h>
class Demo {
public:
int x, y;
Demo(int a, int b) { // Parameterized constructor
x = a;
y = b;
}
};
int main() {
Demo d1(5, 10); // Constructor called with arguments
cout << "x = " << d1.x << endl;
cout << "y = " << d1.y;
return 0;
}
Output : x = 5
y = 10
→Copy Constructor
A copy constructor in C++ is a special member function used to create a new object as a copy of an existing
object of the same class. It is a fundamental part of object initialization and resource management in C++.
Syntax : ClassName(const ClassName &obj);
Example :
#include <iostream.h>
#include <conio.h>
class Demo {
public:
int x;
Demo(int a) { // Parameterized constructor
x = a;
}
Demo(const Demo &d) { // Copy constructor
x = d.x;
}
void display() {
cout << "Value of x = " << x;
}
};
void main() {
clrscr();
Demo d1(10); // Normal constructor
Demo d2 = d1; // Copy constructor
[Link]();
getch();
}
Output : Value of x = 10
[Link]
A destructor is used to destroy the object that have been created by a [Link] destructor have the
same name as the class name preceded by a tilde symbol.
•It is not possible to define more than one destructor.
•It neither require any argument or return any value.
Syntax :
class ClassName {
public:
~ClassName() {
// destructor code
}
};
Example :
#include <iostream.h>
#include <conio.h>
class Demo {
public:
Demo() {
cout << "Constructor called";
}
~Demo() {
cout << "\nDestructor called";
}
};
void main() {
clrscr();
Demo obj; // Constructor is called
getch();
Constraints on Constructor (Definition):
The constraints on a constructor are the rules that must be followed while defining it in a class. A constructor
must have the same name as the class, it does not have any return type, and it is called automatically when an
object is created. A constructor can be overloaded, but it cannot be virtual or inherited.
Constraints on Destructor (Definition):
The constraints on a destructor are the rules that must be followed while defining it. A destructor must have the
same name as the class preceded by a tilde (~) symbol, it does not take any arguments and does not return any
value. Only one destructor is allowed in a class, and it is automatically called when the object is destroyed. It
can be virtual but cannot be overloaded or inherited.