DEV Community

Ram Kumar Shukla
Ram Kumar Shukla

Posted on

class and objects in c++

hey there, today we will talk about class and instances in c++.

Class

c++ supports object-oriented programming and often called user defined data types.
A class is a blueprint of the object. Data and functions within a class are called member of the class.

definition of class

class Circle{
      public:
        double radius; //radius of the circle
}; 
Enter fullscreen mode Exit fullscreen mode

class definition is starts with keyword class followed by classname. Here public means members of the class are accessible from outside the class from anywhere within scope of the class.

Class Objects

Circle circle1; //Declare circle1 of type Circle
Circle circle2; //Declare circle2 of type Circle
Enter fullscreen mode Exit fullscreen mode

class objects/instances are defined by exactly the same way we define basic variables. class name followed by object name.

#include <iostream>
#include <cmath>

using namespace std;

class Circle{
     public:
       double radius;
};

int main(){
  //Objects instantiations
Circle circle1;
Circle circle2;
double area = 0.0; //Store the area of the circle here

circle1.radius = 2.1;
circle2.radius = 5.3;

// Area of the circle1
area = 3.14 * pow(circle1.radius, 2);
cout << "Area of the circle is " << area << endl;

// Area of the circle2
area = 3.14 * pow(circle2.radius, 2);
cout << "Area of the circle is " << area << endl;

return 0;
}
Enter fullscreen mode Exit fullscreen mode

when above code compiled and executed, it will produce a follwing result.

Area of the circle is 13.8474
Area of the circle is 88.2026
Enter fullscreen mode Exit fullscreen mode

Top comments (0)