Below are the topics covered in this chapter
1. Classes in C++
2. Declaring objects
3. The dot operator
4. The arrow operator
1. Classes in C++
Classes in C++ are similar to structures in C. They are used to pack data-members and member functions. The variables defined inside a class are called as data-members. The functions written inside a class are called as member functions.
“class” is the keyword used to define a class.
Example of a class:
Class Student
{
public:
int roll_no;
void display()
{
cout<<”In display function”<<endl;
}
};
Note:
1. By default both data members and member functions are private.
2. There should be a semicolon at the end of the class.
3. The access specifiers should be terminated with a colon “:”.
2. Declaring objects
Once the class is created, we need to create an object. Class is used to specify the structure of the object. An object is a variable/instance of a class.
Declaring an object:
<class_name> <object_name>;
Example:
Student s1;
3. The dot operator
Once you declare an object, that object can access both the data members and member functions of that class. An object can only access “public” members directly. Accessing private or protected members will result in an error.
If we create a simple object, then we use dot “.” operator.
Example:
#include<iostream>
using namespace std;
class Student
{
public:
int roll_no;
void display()
{
cout<<"The roll number of student is = " <<roll_no <<endl;
}
};
int main()
{
Student s1;
s1.roll_no = 10;
s1.display();
}
Output:
The roll number of student is = 10
4. The arrow operator
In the last section we created a simple object. We can also create a pointer of type class and access the public members. If we create a pointer and need to access the members then we have to use “->” operator.
Example:
#include<iostream>
using namespace std;
class Student
{
public:
int roll_no;
void display()
{
cout<<"The roll number of student is = " <<roll_no <<endl;
}
};
int main()
{
Student s1;
Student *s2 = &s1;
s2 -> roll_no = 10;
s2 -> display();
}
Output:
The roll number of student is = 10