Class and Objects in C++
Posted on November 18, 2022 • 1 minutes • 157 words
1. Class
-
A class is a template(prototype) for the object.
-
class is collection of data and its functions/methods
Related videos
Syntax:
class ClassName
{
// body of class
access_specifier:
// data
// methods / functions
};
Example:
class Rectangle
{
public:
// data members
double length;
double width;
// functions / methods
double getArea()
{
return length * width;
}
};
2. Objects
- Object is an instance of class.
- The allocation of memory only occurs when an object is created.
Syntax:
className objectName;
Example:
int main(){
// create objects
Rectangle r1;
Rectangle r2,r3;
}
Accessing Data Members and Functions through objects
We can access functions or data (public) by using . (dot) operator.
Syntax:
objectName.memberName;
objectName.functionName();
Example:
int main(){
// create objects
Rectangle r1;
// accessing the data members
r1.length = 10;
r1.width = 10;
// accessing the member functions
double area = r1.getArea();
std::cout << "Area :" << area;
return 0;
}