Class and Object in c++ | AsgarTech
Class
In C++, a class is a user-defined data type that encapsulates data and methods (functions) that operate on that data. Objects are instances of a class, meaning they are created from the class blueprint and have their own unique set of data and methods.
Here's an example:
#include <iostream>
using namespace std;
// Class declaration
class Rectangle {
private:
int width, height;
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
int area() {
return width * height;
}
};
int main() {
// Object creation
Rectangle rect;
// Object usage
rect.setWidth(5);
rect.setHeight(7);
// Output
cout << "Area of rectangle: " << rect.area() << endl;
return 0;
}
Object
In computer programming, an object is an instance of a class that contains its own unique set of data and functions to manipulate that data. Objects are used in object-oriented programming (OOP) and are created based on a class blueprint.
For example, if you have a class called "Car" that defines the properties and behaviors of a car, you can create multiple objects of the "Car" class with their own specific data values. Each object will have its own set of properties (such as color, make, and model) and behaviors (such as accelerate, brake, and turn).
No comments: