Class

Class is a user-defined blueprint from which objects are created. Basically, a class combines the fields(variables) and methods into a single unit. In C++, classes support advance object oriented programming concepts like inheritance, abstraction etc.

Before entering coding part of Class, we need to be clear with concept called Access Modifiers. Access Modifiers are keywords that define the accessibility of a member, class or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes. There are 3 access modifiers present in C++, let us discuss each with its description.


CODE

EG 1 . Creating Rectangle class with fields and variables

#include <iostream>
using namespace std;

//Creating class called Rectangle with its fields and methods.
class Rectangle {
    //In order to access fields and methods outside class, we need to use Public keyword.
  public:
    double length, width, height;
    double Area() {
        return length * width;
    }
    double Perimeter() {
        return 2 * (length+width);
    }
    double Volume() {
        return Area() * height;
    }
};

int main() {

}



EG 2 . Creating Class called car with fields and variables

#include <iostream>
using namespace std;

class Car {
  public :
    string color;
    int weight, numberOfSeats;
    void Drive() {
        cout << "Start Driving" << endl;
    }
    double CarryingLoadCapacity() {
        return (numberOfSeats*65)+30; //65 is the average weight of a person in kgs, 30kgs for extra load for accessories,fuel etc.
    }
};

int main() {

}




(Click Here, For more exercises)