class and object:
class:
- 1. a class is a way to bind data and associated function together.
- 2. it allows data and function to hidden if necessary for external use.
- 3. defining a class means creating a user defined data type that behaves as built in data.
- 4. once a class has been declared we can create any number of object belonging to that class.
syntax:
class class_name
{
private:
data member;
member function;
public:
data member;
member function;
}; //end of class
Generally data are placed in private section and function are placed in public section.
- 5. class contains both data and function . Data are called data member and function are called member function.
- 6. data and function are defined in private section are not accessible out of the class.
- 7. data and function placed in public section are only accessible from outside the class.
- 8. the word private is optional . the data in function of class by default private.
Object:
An object is an instance of a class.
For example, the Car
class defines the model, brand, and mileage. Now, based on the definition, we can create objects like
Car suv;
Car sedan;
Car van;
Here, suv, sedan, and van are objects of the Car
class. Hence, the basic syntax for creating objects is:
Class_Name object_name;
Example 1: Class and Objects in C++
#include <iostream>
using namespace std;
class Car {
public:
// class data
string brand, model;
int mileage = 0;
// class function to drive the car
void drive(int distance) {
mileage += distance;
}
// class function to print variables
void show_data() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Distance driven: " << mileage << " miles" << endl;
}
};
int main() {
// create an object of Car class
Car my_car;
// initialize variables of my_car
my_car.brand = "Honda";
my_car.model = "Accord";
my_car.drive(50);
// display object variables
my_car.show_data();
return 0;
}
No comments:
Post a Comment