0% found this document useful (0 votes)
11 views37 pages

C++ Module1

The document provides an overview of Object-Oriented Programming (OOP) using C++, detailing key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It contrasts Procedure-Oriented Programming (POP) and OOP, highlighting the advantages of OOP in software development. Additionally, it includes syntax examples and explanations of various inheritance types and access specifiers in C++.

Uploaded by

yashukumar18331
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views37 pages

C++ Module1

The document provides an overview of Object-Oriented Programming (OOP) using C++, detailing key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It contrasts Procedure-Oriented Programming (POP) and OOP, highlighting the advantages of OOP in software development. Additionally, it includes syntax examples and explanations of various inheritance types and access specifiers in C++.

Uploaded by

yashukumar18331
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Name:

OBJECT ORIENTED PROGRAMMING with C++


(PROGRAMMING IN C++)
Course Code: BCS306B

Module-1:
An overview of C++: What is object-Oriented Programming? Introducing C++
Classes, The General Form of a C++ Program.
Classes and Objects: Classes, Friend Functions, Friend Classes, Inline
Functions,
Parameterized Constructors, Static Class Members, When Constructors and
Destructors are Executed, The Scope Resolution Operator, Passing
Objects to functions, Returning Objects, Object Assignment

Differentiate between Procedure Oriented Programming and Object


Oriented Programming.

Procedural-Oriented Programming Object-Oriented Programming


It is known as POP. It is known as OOP.
Procedural programming languages The object-oriented programming
are not as faster as object-oriented languages are faster and more effective
Procedural uses procedures, modules, Object-oriented uses objects, classes,
procedure calls. messages.
Top-down approach Bottom-up approach
Access modifiers are not supported Access modifiers are supported
Functions are preferred over data Security and accessibility are
preferred
If the size of the problem is small, If the size of the problem is big, OOP
POP is preferred. is preferred.
Procedural Programming divides the Object Oriented Programming divides
program into small programs and the program into small parts and refers
refers to them as functions to them as objects.
C, BASIC, COBOL, Pascal, etc. are C++, C#, Java, Python, etc. are the
the examples POP languages examples of OOP languages.
There is no concept of virtual classes. The concept of virtual functions
appears at the time of inheritance.
What is object-Oriented Programming?

 Object-oriented programming is a paradigm for designing a program


using objects and classes. The process simplifies the software
development and maintenance process by providing critical concepts,
such as abstraction, encapsulation, inheritance, data binding,
polymorphism, etc.

The main purpose of introducing Object Oriented Programming in C++ is to


introduce object orientation in C programming.

Basic OOP Concepts in C++


The following basic concepts are the building blocks of OOPs in C++:
1. Class
2. Object
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance

[Link]

A class is a user-defined blueprint or prototype from which objects are created.


It represents the set of properties or methods that are common to all objects of
one type. Using classes, you can create multiple objects with the same behavior
instead of writing
their code multiple times. In general, class declarations in C++ can include these
components.
 Access Specifiers: A class can have members defined as public, private,
or protected to control accessibility.
 Class Name: The class name should follow naming conventions, usually
starting with a capital letter.
 Body: The class body is enclosed with braces {} and defines data
members and member functions.
2. Object

An Object is a basic unit of Object-Oriented Programming that represents real-


life entities. A typical C++ program creates many objects, which interact with
each other by invoking methods. The objects are what perform your code, they
are the part of your code visible to the user. An object mainly consists of:
 State: It is represented by the data members (attributes) of an object. It
also reflects the properties of an object.
 Member Function: A member function is a collection of statements that
perform some specific task and may return the result to the caller.
 Behavior: It is represented by the member functions of an object. It also
reflects the response of an object to other objects.
 Identity: It is a unique name or reference given to an object that enables it
to interact with other objects.
Syntax:
className objectName;

3. Abstraction

Abstraction in C++ is the process of hiding the implementation details


and only showing the essential details or features to the user. It allows to focus
on what an object does rather than how it does it.
In C++ abstraction is achieved using abstract classes (classes that have at least
one pure virtual function).
4. Encapsulation

Encapsulation is defined as the process of wrapping data and the methods into a
single unit, typically a class. It is like a protective shield that prevents the data
from being accessed by the code outside the shield.
 Technically, in encapsulation the variables or the data in a class is hidden
from any other class and can be accessed only through any member
function of the class in which they are declared.
 In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does.
 Encapsulation can be achieved by declaring all the variables in a class as
private and writing public methods in the class to set and get the values of
the variables.

5. Polymorphism

The word polymorphism means having many forms, and it comes from the
Greek words poly (many) and morph (forms), this means one entity can take
many forms. In C++, polymorphism allows the same method or object to
behave differently based on the context, specially on the project's actual runtime
class.

Types of Polymorphism

Polymorphism in C++ is mainly of 2 types as mentioned below:


 Function Overloading
 Function Overriding

Function Overloading and Function Overriding

1. Function Overloading : Also known as compile-time polymorphism, this


occurs when two or ore functions in the same class share the same name but
have different parameters lists (different number or types of parameters). The
return type of these functions may or may not be same.
2. Function Overriding : Also, known as run-time polymorphism, this occurs
when a function in the derived class has the same name, return type, and
parameters as a function in the base class. In C++, this is achieve using virtual
functions, so that the derived class provides its own implementation of the
method.
5. Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is


the mechanism in C++ by which one class is allowed to inherit the features
(data members and member functions) of another class. We achieve inheritance
by using the : symbol followed by an access specifier (public, private, or
protected). Inheritance is also known as an "is-a" relationship.

Example: Dog, Cat, Cow and be Derived Class of Animal Base Class.

Syntax:

class Base
// members of base class
}
class Derived : access_specifier Base {
// members of derived class
};

Let us discuss some frequently used important terminologies:


 Superclass: The class whose features are inherited is known as
superclass (also known as base or parent class).
 Subclass: The class that inherits the other class is known as subclass
(also known as derived or extended or child class). The subclass can add
its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of "reusability", i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class.
In C++, we have 5 types of inheritances:
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance

[Link] Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e one
base class is inherited by one derived class only.

Syntax:
class Base {
// members of base cla
};

class Derived: access_specifier Base {


// members of derived class
};

Example Program

class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

class Dog : public Animal {


public:
void bark() {
cout << "Barking..." << endl;
}
};

[Link] Inheritance
In multilevel inheritance, a derived class is created from another derived class
and that derived class can be derived from a base class or any other derived
class. There can be any number of levels.
Syntax :
class A { };
class B : public A { };
class C : public B { };

class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};

class Mammal : public Animal {


public:
void breathe() { cout << "Breathing..." << endl; }
};

class Dog : public Mammal {


public:
void bark() { cout << "Barking..." << endl; }
};

3. Multiple Inheritance
In Multiple inheritance, one class can have more than one superclass and inherit
features from all parent classes

Syntax :

class Derived : access_specifier Base1, access_specifier Base2 {


// members of derived class
};

4. Hierarchical Inheritance:
In hierarchical inheritance, more than one subclass is inherited from a single
base class. i.e. more than one derived class is created from a single base class.
For example, cars and buses both are vehicle.

Syntax :
class A { };
class B : public A { };
class C : public A { };
EXAMPLE PROGRAM
class Shape {
public:
void draw() { cout << "Drawing shape" << endl; }
};

class Circle : public Shape {


public:
void area() { cout << "Circle area" << endl; }
};

class Rectangle : public Shape {


public:
void area() { cout << "Rectangle area" << endl; }
};

5. Hybrid Inheritance
Combination of two or more types of inheritance.(Often involves multiple +
multilevel inheritance).

Syntax :

class Vehicle {
public:
void fuel() { cout << "Fuel needed" << endl; }
};

EXAMPLR PROGRAM

class Engine {
public:
void power() { cout << "Engine power" << endl; }
};
class Car : public Vehicle {
public:
void drive() { cout << "Car drives" << endl; }
};

class SportsCar : public Car, public Engine {


public:
void speed() { cout << "High speed" << endl; }
};

Inroducing C++ Classes

Class in C++ is the building block that leads to Object-Oriented programming.


It 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.
What is a Class in C++?
 A class in C++ is a blueprint or template that defines how an object will
look and behave.
 It combines data (variables) and functions (methods) into a single unit.
Think of a class as a plan for a house, and objects are the actual houses built
using that plan.

When you write a class in C++, you can define its functions in two ways:

1. Inside the class definition: Function body is written inside the class.
[Link] the class definition: Function is just declared inside the class,
and the actual function body is written later, outside the class using the scope
resolution operator (::).

Example:
#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;
void display(); // Function declared (not defined here)
};

// Function defined outside the class using ::


void Student::display() {
cout << "Name: " << name << ", Age: " << age << endl;
}

int main() {
Student s1;
[Link] = "Rahul";
[Link] = 20;

[Link](); // Calls the function


return 0;
}

Why Do We Need Classes?

Before classes, in C, we usually kept data and functions separate.

But in real life:


 A car has properties (color, speed, brand) → data
 And actions (drive, brake, honk) → functions
 Classes in C++ allow us to bundle these together in a single structure,
making the program more organized, reusable, and closer to real-world
modeling.

Defining Class:

A class is defined in C++ using the keyword class followed by the name of the
class. The body of the class is defined inside the curly brackets and terminated
by a semicolon at the end.
Declaring Objects
When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined in
the class, you need to create objects.

Syntax:
ClassName ObjectName;

 Accessing member functions: The data members and member functions


of the class can be accessed using the dot(‘.’) operator with the object.
For example, if the name of the object is obj and you want to access the
member function with the name printName() then you will have to write
[Link]().

 Accessing Data Members:The public data members are also accessed in


the same way given however the private data members are not allowed to
be accessed directly by the object. Accessing a data member depends
solely on the access control of that data member.

// C++ program to demonstrate accessing of data members

#include <iostream.h> using namespace std;


class AIT {
// Access specifier public:
// Data Members
string CSE;
// Member Functions()
void printname() { cout << “CSE name is:" << CSE; }
};
int main()
{
// Declare an object of class geeks
AIT obj1;
// accessing data member [Link] = “3 A & B";
// accessing member function
[Link]();
return 0;
}

GENERAL FORM OF C++ PROGRAM

Although individual styles will differ, most C++ programs will have this general
form:
#includes
base-class declarations
derived class declarations
nonmember function prototypes
int main( )
{
//...
}
nonmember function definitions
In most large projects, all class declarations will be put into a header file and
included with each module. But the general organization of a program remains
the same.

CLASSES :

Classes are created using the keyword class. A class declaration defines a new
type that links code and data. This new type is then used to declare objects of
that class.

class class-name {
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ...
access-specifier:
data and functions
} object-list;

The object-list is optional. If present, it declares objects of the class

Create a Class :

To create a class, use the class keyword:


Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable) string myString; // Attribute (string
variable)
};

Create an Object :
To 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:

class MyClass { // The class


public: // Access specifier
int myNum;
// Attribute (int variable) // Attribute (string variable)
string myStr
ing;
};
int main() { MyClass myObj;
//
Create an object of MyClass
// Access attributes and set values [Link] = 15;
[Link] = "Some text";
// Print attribute values
cout << [Link] << "\n"; cout << [Link];
return 0;
}

ACCESS-SPECIFIER is one of these three C++ keywords:

i) private ii) public iii) protected

1. By default, functions and data declared within a class are private to that
class and may be accessed only by other members of the class.
2. The public access specifier allows functions or data to be accessible to
other parts of your program.
3. The protected access specifier is needed only when inheritance is
Involved.
4. A protected member variable or function is very similar to a private
member but it provided one additional benefit that they can be accessed
in child classes which are called derived classes.
5. Once an access specifier has been used, it remains in effect until either
another access specifier is encountered or the end of the class declaration
is reached.
6. A class can have multiple public, protected, or private labeled sections.
Each section remains in effect until either another section label or the
closing right brace of the class body is seen.
7. The default access for members and classes is private.

Syntax:

class Base {
public: // public members go here protected: // protected members go here
private: // private members go here
};
FRIEND FUNCTION

 In C++, normally the private and protected members of a class cannot be


accessed directly from outside the class.
 A friend function can access the private and protected data of a class. We
declare a friend function using the friend keyword inside the body of the
class.
 But sometimes, we may want a non-member function to access these
private/protected members.
 To allow this, we declare that function as a friend function inside the
class using the keyword friend.
 A friend function is not a member of the class.
But it has special permission to access the private and protected members of the
class.

Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Example program

#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int l) { length = l; }

// Friend function declaration


friend void printLength(Box b);
};

// Friend function definition


void printLength(Box b) {
// Can access private member 'length'
cout << "Length of box: " << [Link] << endl;
}

int main() {
Box b1(10);

// Even though printLength is not a member of Box,


// it can still access private data
printLength(b1);

return 0;
}

EXAMPLE 2:

#include <iostream>
using namespace std;
class demo
{
private:
int a=5;
friend void display(demo);//friend function declaration };
void display(demo d) //friend function defination {
cout<<"a: "<<d.a<<endl; //access of private data
}
int main()
{
demo d;
display(d); //calling a friend function return 0;
}
FRIEND CLASSES

In C++ , a friend class is a class that is given access to the private and protected
members of another class.
We can also use a friend Class in C++ using the friend keyword. For example,

Syntax:

class ClassB;
class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB; ... .. ...
}
class ClassB {
... .. ...
}

 When a class is declared a friend class, all the member functions of the
friend class become friend functions.
 Since ClassB is a friend class, we can access all members of ClassA from
inside ClassB.
 However, we cannot access members of ClassB from inside ClassA. It is
because friend relation in C++ is only granted, not taken

Example program:

class ClassB; // Forward declaration

class ClassA {
private:
int dataA;

public:
ClassA(int x) : dataA(x) {}

// Declare ClassB as a friend


friend class ClassB;
};
class ClassB {
public:
void showData(ClassA obj) {
// Can access private members of ClassA
cout << "Data from ClassA: " << [Link] << endl;
}
};

Example2 :

#include <iostream>
using namespace std;
class test1
{
int a,b;
public:
void get()
{
cout<<"enter 2 integers";
cin>>a>>b;
}
friend class test2;
//defining friend class
};
class test2
{
test1 t1;
public:
void put()
{
[Link]();
cout<<"a: "<<t1.a<<endl; cout<<"b: "<<t1.b<<endl;
}
};
int main()
{
test2 t2;
[Link]();
}

INLINE FUNCTIONS

An inline function is a function in which the compiler places a copy of the


function’s code directly at the point where the function is called, instead of
performing a regular function call.
This avoids the overhead of function calls (like jumping to function code and
returning back).
It is declared using the keyword inline

Syntax:
inline return_type function_name(parameters) {
// function body
}

Example 1:

#include <iostream>
using namespace std;

// Inline function definition


inline int square(int x) {
return x * x;
}

int main() {
cout << "Square of 5 = " << square(5) << endl;
cout << "Square of 10 = " << square(10) << endl;
return 0;
}

Example 2:

#include<iostream>
Using namespace std;
Class Rectangle
{
Private :
int length,width;
public:
inline void setvalue(int l,int w)
{
Length = l;
Width = w;
}
inline int area()
{
Return length * width;
}
inline int perimeter()
{
return 2*(length + width);
}
int main()
{
Rectangle rect;
[Link](10,5);
cout<<”Area of Rectangle:”<<[Link]()<<endl;
cout<<”perimeter of Rectangle:”<<[Link]()<<endl;
return 0;
}

What is a Constructor in C++?

 A constructor is a special member function of a class in C++ that is


automatically called when an object of that class is created.
 Its main purpose is to initialize the data members of the class.

Characteristics of Constructors

 The name of the constructor is the same as the class name.


 It has no return type, not even void.
 It is automatically invoked when an object is created.
 Constructors can be overloaded (we can have multiple constructors in the
same class).

Types of Constructors in C++

Default Constructor

 A constructor with no parameters.


 Initializes objects with default values.

Ex
#include <iostream>
using namespace std;

class Student {
int age;
public:
// Default constructor
Student() {
age = 18;
cout << "Default constructor called. Age = " << age << endl;
}
};

int main() {
Student s1; // Constructor automatically called
return 0;
}
Parameterized Constructor

 A constructor that takes arguments.


 Allows initializing objects with specific values.

Ex
#include <iostream>
using namespace std;

class Student {
string name;
int age;
public:
// Parameterized constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Parameterized constructor called. Name = "
<< name << ", Age = " << age << endl;
}
};

int main() {
Student s1("Anjali", 20); // Constructor called with parameters
return 0;
}

Copy Constructor

A constructor that creates a new object as a copy of an existing object.

#include <iostream>
using namespace std;

class Student {
string name;
public:
// Parameterized constructor
Student(string n) {
name = n;
}

// Copy constructor
Student(const Student &s) {
name = [Link];
cout << "Copy constructor called. Name = " << name << endl;
}
};

int main() {
Student s1("Anjali");
Student s2(s1); // Copy constructor called
return 0;
}

Why use Constructors?

 To automatically initialize objects.


 To make code cleaner and avoid writing initialization code repeatedly.
 To handle different ways of creating objects (default, parameterized,
copy).

The scope resolution operator (::) in C++ is used to access a global variable,
function, or class member that is hidden by a local declaration or to define a
class member function outside the class.
It helps the compiler identify which scope (or namespace) a particular identifier
belongs to.
::identifier

syntax
ClassName::member
ex
NamespaceName::member

Uses of Scope Resolution Operator (::)


1. To access a global variable when a local variable has the same name
When a local variable and a global variable have the same name, the local one
hides the global.
You can use :: to access the global variable.

#include <iostream>
using namespace std;

int x = 10; // Global variable

int main() {
int x = 20; // Local variable
cout << "Local x = " << x << endl;
cout << "Global x = " << ::x << endl; // Using scope resolution
return 0;
}

Output

Local x = 20
Global x = 10

Local Variables
🔹 Definition:
A local variable is a variable that is declared inside a function, block, or class
method.
It can be used only within that specific block where it is defined.
When the function finishes executing, the local variable is destroyed
automatically.

2. Global Variables
🔹 Definition:
A global variable is declared outside all functions and classes.
It can be used anywhere in the program — inside any function or class.
Global variables remain in memory for the entire duration of the program.

#include <iostream>
using namespace std;

int x = 100; // Global variable

int main() {
int x = 50; // Local variable
cout << "Local x = " << x << endl; // Prints 50
cout << "Global x = " << ::x << endl; // Prints 100 using scope resolution
operator
return 0;
}

What are Static Class Members?

 In C++, when you declare a static data member or static function member
inside a class:
 The member belongs to the class itself, not to any specific object.
 Only one copy of a static member exists, no matter how many objects of
the class are created.
 It is shared among all objects of that class.

Static Data Members

 Declared inside a class with the keyword static.


 Stored in global memory, not inside each object.
 Must be defined outside the class (unless initialized with constexpr or
inline in modern C++).
 Can be accessed using object name or class name.

#include <iostream>
using namespace std;

class Student {
static int count; // Declaration of static data member
public:
Student() {
count++; // Every time object is created, count increases
}

void showCount() {
cout << "Number of students = " << count << endl;
}
};

// Definition of static member outside the class


int Student::count = 0;

int main() {
Student s1, s2, s3;
[Link]();
[Link]();
[Link]();

return 0;
}
Output

Number of students = 3
Number of students = 3
Number of students = 3

Static Member Functions

 Declared inside a class with static.


 Can only access static data members and other static member functions
(since they don’t belong to any object).
 Can be called using the class name without creating an object.

#include <iostream>
using namespace std;

class Student {
static int count;
public:
Student() { count++; }

// Static member function


static void showCount() {
cout << "Total students = " << count << endl;
}
};

int Student::count = 0;

int main() {
Student s1, s2;
Student::showCount(); // Called without object

Student s3;
Student::showCount();

return 0;
}

Output

Total students = 2
Total students = 3

When Constructors and destructors are Executed

Constructor in C++
A constructor is a special member function of a class that is automatically called
when an object is created.
Its main purpose: initialize data members of the object.

Key points:
 Has the same name as the class.
 No return type (not even void).
 Can be default, parameterized, or copy constructor.
 Can be overloaded.

#include <iostream>
using namespace std;

class Student {
string name;
int age;
public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Constructor called: " << name << " is " << age << " years old."
<< endl;
}
};

int main() {
Student s1("Anjali", 20); // Constructor automatically executed
Student s2("Rahul", 22); // Another constructor call
return 0;
}
Output

Constructor called: Anjali is 20 years old.


Constructor called: Rahul is 22 years old.

Destructor in C++

A destructor is a special member function that is automatically called when an


object goes out of scope or is explicitly deleted.
Its main purpose: release resources (like memory, file handles, network
connections).
Key points:
 Same name as class, preceded by ~.
 No return type, no parameters.
 Cannot be overloaded (only one destructor per class).

#include <iostream>
using namespace std;

class Student {
string name;
public:
// Constructor
Student(string n) {
name = n;
cout << "Constructor called for " << name << endl;
}

// Destructor
~Student() {
cout << "Destructor called for " << name << endl;
}
};

int main() {
Student s1("Anjali");
Student s2("Rahul");
cout << "Inside main function." << endl;
return 0;
}

Output

Constructor called for Anjali


Constructor called for Rahul
Inside main function.
Destructor called for Rahul
Destructor called for Anjali
Passing Objects to functions

In C++ programming, we can pass objects to a function in the same way as


passing built-in data types.

The C++ functions can receive objects in multiple ways, depending upon how
you want the function to interact with the object. You can either define functions
that can modify the original objects or define functions that will make a copy of
original object and modify the copy without affecting the original object.

Syntax:
function_name (object_name)
#include<iostream>
using namespace std;
class A
{
public:
int age = 20;
char ch = 'A';
// function that has objects as parameters
void display(A &a)
{
cout << "Age = " << [Link] << endl; cout << "Character = " << [Link] << endl;
}
};
Pass by Value
int main()
{
A obj;
[Link](obj);
return 0;
}
Output Age = 20
Character = A
This creates a shallow local copy of the object in the function scope. Things
you modify here won't be reflected in the object passed to it. Pass by Reference
This passes a reference to the object to the function. Things you modify here
will be reflected in the object passed to it. No copy of the object is created.
Anobject can be passed to a function just like we pass structure to a function.
Here in class A wehave a function display() in which we are passing the object
of class A. Similarly we can pass the object of another class to a function of
different class.

Example 1: C++ Pass Objects to Function

#include <iostream>
using namespace std;
class Person
{
public: string name;
Person(string n)
{
name = n;
}
void display()
{
cout << "Name: " << name << endl;
}
};
void changeName(Person p)
{
[Link] = "Alice";
// This change won't reflect outside
}
int main()
{
Person p1("John"); changeName(p1);
[Link]();
return 0;
}

// Output: Name: John

Returning Objects

Returning Objects A function may return an object to the caller

#include <iostrem>
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;
}
Output
Marks 1 = 96.5 Marks 2 = 75.0
In this program, we have created a function createStudent() that returns an
object of Student class. Wehavecalled createStudent() from the main() method.
Call function student1 = createStudent(); Here, we are storing the object
returned by the createStudent() method in the student1

An object can be returned by a function using the return keyword. There is no


specific technique to return an object, you can simply return it just like any
other data type returning from the function. Consider the following syntax.

Syntax

The syntax for returning an object from the function is as follows:


class_name function_name(class_name obj1) // Passing object
{
class_name obj2;
// code lines
return obj2; // Returning object
}

Object Assignment in C++

Object assignment in C++ refers to assigning the contents of one object to


another existing object of the same class using the assignment operator (=).
It means copying the data members (values) of one object into another after
both objects have already been created.

syntax
obj2 = obj1;

Ex;
#include <iostream>
using namespace std;

class Student {
string name;
int age;
public:
Student(string n, int a) {
name = n;
age = a;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student s1("Anjali", 20);
Student s2("Riya", 21);

cout << "Before assignment:\n";


[Link]();
[Link]();

// Object assignment
s2 = s1; // copies values from s1 to s2

cout << "\nAfter assignment:\n";


[Link]();
[Link]();

return 0;
}

Before assignment:
Name: Anjali, Age: 20
Name: Riya, Age: 21

After assignment:
Name: Anjali, Age: 20
Name: Anjali, Age: 20

You might also like