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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay