Object and Class in C++
C++ Object and Class
In C++, a class is a user-defined type that represents a collection of data and functions that operate on that data. It is a way to encapsulate data and behavior in a single unit. On this page you will be understanding about Object and Class in C++. An object is an instance of a class. Each object has its own separate instance of the class’s data members and can have different values for those data members.
Object and Class in C++
- In C++ programming language, Here is an example of a simple class definition in C++.
- To create an object of this class, you would use the following syntax:
Point p;
This class, called “Point”, has two data members (x and y) and two member functions (setX and setY).
class Point { public: int x; int y; void setX(int newX) { x = newX; } void setY(int newY) { y = newY; } };
This class, called “Point”, has two data members (x
and y
) and two member functions (setX
and setY
). The public:
keyword indicates that the data members and member functions following it are accessible from outside the class.
You can then access the object’s data members and call its member functions like this:
p.x = 10; p.setY(20);
You can also define multiple objects of the same class:
Point p1, p2;
Each object has its own separate instance of the class’s data members and can have different values for those data members.
Member Functions in Classes in C++
// C++ program to demonstrate function #include <iostream> using namespace std; class Rectangle { private: int length; int width; public: void setLength(int len) { length = len; } void setWidth(int wid) { width = wid; } int getArea() { return length * width; } }; int main() { Rectangle rect; rect.setLength(5); rect.setWidth(3); cout << "The area of the rectangle is " << rect.getArea() << endl; return 0; }
Output:
The area of the rectangle is 15
To use this class, you would first create an object of the class and then call the object’s member functions to set the values of its data members. Here is an example of how you might use the Point
class:
Example:
#include <iostream> using namespace std; class candidate { public: int id; string name; }; int main() { candidate s1; s1.id = 201; s1.name = "AmitabhBachan"; cout << s1.id << endl; cout << s1.name << endl; return 0; }
Output:
201 AmitabhBachan
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment