+ 1
What is abstract-classes in c++? explain me with simple example?
2 Respostas
+ 4
Abstract classes are mainly interfaces. They are there mostly to help 'smoothen' the other classes that are trying to inherit from it.
A class is simply made abstract just by making a prue virtual function.
class TEST{
public :
virtual double SomeDouble() = 0; //Make it virtual
}
and that is it, TEST became an abstract class. All you have to do is to place a '= 0' in the declaration of the function, simple as that.
0
An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions.A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract) derived class. This is indicated in the declaration with the syntax " = 0" in the member function's declaration.
Example
class AbstractClass {
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes
// this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.
void NonAbstractMemberFunction2();
};
In general an abstract class is used to define an implementation and is intended to be inherited from by concrete classes. It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member function of the base class. Otherwise, if any member function of the base class is left undefined, we will create a new abstract class (this could be useful sometimes).
Sometimes we use the phrase "pure abstract class," meaning a class that exclusively has pure virtual functions (and no data). The concept of interface is mapped to pure abstract classes in C++, as there is no "interface" construct in C++ the same way that there is in Java.