Classes and Objects in C++ – 2
Written by
In the previous chapter, we read about the classes and their importance in C++. Now, in this chapter, we will learn more about the classes and objects in C++.
From our previous chapters we know that a class is nothing but a blueprint that means that a class has no existence in the real world.
In order to create an existence for a class in the real world, we need to create an instance of that class. This instance is created with the help of objects.
Objects are those entities which actually have a real-world existence. We can access any members of a class and use its methods with the help of these objects.
Let us understand this with the help of an example.
Suppose, a student, he has an id, a name and is enrolled in a course. Now, this student performs some functions also, like he enrolls himself in a course, he pays fee for that course and studies the subjects assigned to him. Thus, student is a class, now this student has no real-world existence.
Let us define this student class in C++:
class Student
{
int id;
char course[10], name[30];
public:
void enroll()
{
course = “C++ Programming”;
float fee=5000;
cout<< “Course:”<<course<<”\nFee:”<<fee;
}
};
Above is a class student as defined in our given example, now in order to access the members of this class, we need to create an object of student.
Object Creation in C++:
We can create objects as follows:
Class_name Object_name;
This line creates an object of the given class. For Example, to create an object of student class, we write:
Student s;
Accessing Members of a class:
We can access the public members of a class using the object that we have created. This can be depicted here:
s.enroll();
Since, enroll() is a public member function of the class, thus we can access it anywhere in our C++ program with the help of the object created. Now, let us look at the whole code:
class Student
{
int id;
char course[10], name[30];
public:
void enroll()
{
course = “C++ Programming”;
float fee=5000;
cout<< “Course:”<<course<<”\nFee:”<<fee;
}
};
void main()
{
Student s; //creating object of student of class
s.enroll(); //accessing public members of student class
s.id=100;
/generates an error as id is a private member of student class and thus inaccessible/
getch();
}