Recap - Shape Calculator
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 63 of 104.
Challenge
EasyLet's build a shape calculator that brings together everything you've learned about polymorphism. You'll create an abstract Shape class and implement concrete shapes that calculate their area and perimeter, all accessible through a common interface.
You'll organize your code across four files:
Shape.h: Define an abstractShapeclass that serves as the blueprint for all shapes. Your base class should have:- A protected
std::string namemember to identify the shape - A constructor that initializes the name
- Pure virtual methods
area()andperimeter()that returndouble - A
getName()method that returns the shape's name - A virtual destructor
- A protected
Circle.h: Implement aCircleclass that inherits fromShape:- A private
double radiusmember - A constructor taking the radius (set the name to
"Circle") - Implement
area()using the formula: 3.14159 * radius * radius - Implement
perimeter()using: 2 * 3.14159 * radius
- A private
Rectangle.h: Implement aRectangleclass that inherits fromShape:- Private
double widthanddouble heightmembers - A constructor taking width and height (set the name to
"Rectangle") - Implement
area()as width * height - Implement
perimeter()as 2 * (width + height)
- Private
main.cpp: Read four inputs (each on a separate line):- Circle radius (double)
- Rectangle width (double)
- Rectangle height (double)
- Second circle radius (double)
Create all three shapes dynamically and store them in an array of
Shape*pointers. Loop through the array and for each shape, print its information in this format:<name>: Area: <area> Perimeter: <perimeter>Print a blank line between each shape. Clean up your dynamically allocated objects when finished.
For example, with inputs 5, 4, 6, and 3:
Circle:
Area: 78.5397
Perimeter: 31.4159
Rectangle:
Area: 24
Perimeter: 20
Circle:
Area: 28.2743
Perimeter: 18.8495Notice how the same printShapeInfo logic works for any shape type — this is the power of polymorphism. Your code processes circles and rectangles identically through the Shape interface, and each shape knows how to calculate its own measurements. Use the override keyword on all overridden methods to ensure correct function signatures.
Try it yourself
#include <iostream>
#include "Shape.h"
#include "Circle.h"
#include "Rectangle.h"
using namespace std;
int main() {
// Read inputs
double circleRadius1, rectWidth, rectHeight, circleRadius2;
cin >> circleRadius1;
cin >> rectWidth;
cin >> rectHeight;
cin >> circleRadius2;
// TODO: Create an array of Shape* pointers with 3 elements
// Shape* shapes[3];
// TODO: Create shapes dynamically and store in array
// shapes[0] = new Circle(...);
// shapes[1] = new Rectangle(...);
// shapes[2] = new Circle(...);
// TODO: Loop through the array and print each shape's info
// Format:
// <name>:
// Area: <area>
// Perimeter: <perimeter>
// (blank line between shapes, but not after the last one)
// TODO: Clean up dynamically allocated objects
// delete shapes[i];
return 0;
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container