Objects
An object is an instance of a class.
If a class is considered a blueprint, an object is an actual entity created using that blueprint.
Example:
class Student
{
public:
int roll;
};
Student s1;
Student s2;
Here:
- Student is a class.
- s1 is an object of Student.
- s2 is another object of Student.
Each object has its own copy of the class’s non-static data members
Declaration of Objects
Objects can be declared after defining a class.
Example:
class Student
{
public:
int roll;
};
Student s1;
Student s2;
Multiple objects can also be declared in one statement:
Student s1, s2, s3;
The objects s1, s2 and s3 are separate instances of the Student class.
Accessing Class Members Using Objects
Public members of a class can be accessed using an object and the dot (.) operator.
Example:
class Student
{
public:
int roll;
void display()
{
cout << roll;
}
};
int main()
{
Student s;
s.roll = 25;
s.display();
return 0;
}
Here:
s.roll = 25;
accesses the data member roll.
And:
s.display();
calls the member function display().
Important Point
The dot operator . is commonly used to access public members through an object.
Global and Local Objects
Objects can be declared at different places in a program.
Depending on where an object is declared, it may be a global object or a local object.
Global Object
An object declared outside all functions is called a global object.
Local Object
An object declared inside a function or block is called a local object.
Nesting of Member Functions
A member function can call another member function of the same class.
This is commonly referred to as nesting of member functions.
Nested Class
A nested class is a class declared inside another class.
Objects as Function Arguments
An object can be passed to a function just like other data types.
There are two common ways of passing an object to a function:
- Pass by value
- Pass by reference
Passing Object by Value
When an object is passed by value, a copy of the object is passed to the function.
Changes made to the parameter inside the function do not change the original object.
Passing Object by Reference
An object can also be passed by reference.Here reference to the original object is passed.The function works with the original object.Changes made affect the original object
Static Class Members
Normally, each object has its own copy of non-static data members.
Sometimes, however, we want a particular piece of data to be shared by all objects of a class.
For this purpose, C++ provides static members.
Static class members are mainly of two types:
- Static data members
- Static member functions
Static Data Member
A static data member is shared by all objects of a class.
Unlike an ordinary data member, only one shared copy exists for the class.
.
Static Member Function
A static member function belongs to the class rather than to a particular object.
It can be called using the class name.