YouTip LogoYouTip

Cpp Interfaces

# C++ Interfaces (Abstract Classes) An interface describes the behavior and functionality of a class, without completing the specific implementation of the class. C++ interfaces are implemented using **abstract classes**, which are not to be confused with data abstraction, a concept that separates implementation details from related data. If at least one function in a class is declared as a pure virtual function, then the class is abstract. Pure virtual functions are specified by using "= 0" in the declaration, as shown below: class Box{public: // Pure virtual function virtual double getVolume() = 0; private: double length; // Length double breadth; // Breadth double height; // Height}; The purpose of designing an **abstract class** (often called an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects; they can only be used as **interfaces**. Attempting to instantiate an object of an abstract class will result in a compilation error. Therefore, if a subclass of an ABC needs to be instantiated, it must implement each pure virtual function. This means that C++ supports the declaration of interfaces using ABCs. If a pure virtual function is not overridden in a derived class and an attempt is made to instantiate an object of that class, it will result in a compilation error. A class that can be used to instantiate objects is called a **concrete class**. ## Example of an Abstract Class Look at the following example, where the base class Shape provides an interface **getArea()**, which is implemented in the two derived classes Rectangle and Triangle: ## Example #includeusing namespace std; // Base class class Shape{public: // Pure virtual function providing interface framework virtual int getArea() = 0; void setWidth(int w){width = w; }void setHeight(int h){height = h; }protected: int width; int height; }; // Derived class class Rectangle: public Shape{public: int getArea(){return(width * height); }}; class Triangle: public Shape{public: int getArea(){retur
← Cpp Class Access ModifiersInput Output Operators Overloa β†’