C++ Online Compiler
Example: Circle Area using Class and Object in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Circle Area using Class and Object #include <iostream> #include <cmath> // Required for M_PI constant // Define PI if not available via cmath (e.g., older compilers or specific standards) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // Define the Circle class class Circle { private: double radius; // Member variable to store the radius public: // Constructor to initialize the radius Circle(double r) { radius = r; } // Member function to calculate the area of the circle double calculateArea() { return M_PI * radius * radius; } // Optional: Member function to display circle information void displayCircleInfo() { std::cout << "Radius: " << radius << std::endl; std::cout << "Area: " << calculateArea() << std::endl; } // Optional: Getter for radius double getRadius() { return radius; } }; int main() { // Step 1: Declare a variable for the radius double r; // Step 2: Prompt the user to enter the radius std::cout << "Enter the radius of the circle: "; std::cin >> r; // Step 3: Validate the radius if (r < 0) { std::cout << "Radius cannot be negative. Please enter a positive value." << std::endl; } else { // Step 4: Create an object of the Circle class // The constructor Circle(r) is called to initialize the object's radius Circle myCircle(r); // Step 5: Call the calculateArea() member function using the object double area = myCircle.calculateArea(); // Step 6: Display the result std::cout << "The area of the circle with radius " << myCircle.getRadius() << " is: " << area << std::endl; // Or using the displayCircleInfo method: // myCircle.displayCircleInfo(); } return 0; }
Output
Clear
ADVERTISEMENTS