Explain about Class Objects in C++

Estudies4you

Class Objects

Q13. Write in detail about class objects.
Answer:

Object
An object can be defined as an instance of a class which is used to access the members of a class.
Declaration of Objects to a Class
The declaration of objects to a class is similar with the declaration of variables to datatypes. The method of defining the declared class objects is known as class instantiations. For every object, a separate memory is allocated. Memory allocation is done only for the member functions of each class object. An object can be declared in two methods. They are as follows,
Method 1
An object can be declared as a normal variable.
Syntax
Classname objectname;
Example
Student stul;
Method 2
The object can also be declared as a pointer variable.
Syntax
classname *objectname;
Example
Student *stu2;
Accessing Class Members
The members of a class can be accessed by objects using,
(i) dot operator (.)
(ii) arrow operator(→)

(i) DotOperator (.)
The syntax to access class members using dot operator is as follows,
Classobject dot operator membervariable
Example
An example to access class members using dot operator is as follows,
stu.setMarks();
In the above example, stu is an object, .(dot) is an operator used for normal object and setMarks() is the member function of the class.

(ii) Arrow Operator (→)
Another method to access class member is by using arrow () operator. The arrow () operator is used by the objects that are declared.as pointers.
classobject arrowoperator *membervariable

Example
class Student
{
private:
int stdId;
char stdName( );
public : :
void setMarks( );

};
The pointer can be created as follows:
student stul, *stu2;

The member functions of a class can be accessed by using pointer object.

Example
stu2setMarks( );
*stu2 is a pointer object to the class student and arrow operator is accessing the member function setMarks( ).
Accessing class members depends on place where the object is declared.
  1. If declaration of object is done in any of the member functions ,then it can access the public as well as the private member variables.
  2. If declaration of object is done anywhere other than member functions, then the object can access only public member variables.
Program
//An example program to demonstrate object declaration is as given below,
#include <iostream.h>
#include<conio.h>
class student
{
private:
int r_no;
public:
char name[20];
int func1()
{
r_no = 29;
return r_no;
}
};
int main()
{
clrscr();
student stul; //creating object stul of class type student
cout <<" The r_no is:"<<stul .func1();
getchQ;
return 0;
}
Output
arrow operator in c++,accessing class members in c++,dot operator in c++,

In the above program, a class named as student is declared. The member variables are declared as private and member functions are declared as public. The class members are accessed by. using objects. The objects such as stul access the member functions.


To Top