First, I am new to C++. I open a header file for each and every C++ class. Now I am in a need of creating an abstract class. Following is my code
Magic.h
#pragma once class Magic { public: Magic(void); ~Magic(void); virtual void display()=0; };
Magic.cpp
#include "Magic.h" Magic::Magic(void) { } Magic::~Magic(void) { }
Now, as you know I can't add following to the cpp file.
Magic::display() { }
So, do I really need a .cpp file for an Abstract class? Or else, am I incorrectly calling display()
in .cpp file?
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.
cpp needs it because it is defining the code that backs the class interface, so it needs to know what that interface is. Main. cpp needs it because it is creating a Foo and invoking its behavior, so it has to know what that behavior is, the size of a Foo in memory and how to find its functions, etc.
Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature; they cannot define the implementation.
Can it have constructor? Yes it can and the purpose is to initialize local variables from the base class. You should avoid using public constructor in Abstract and use protected only.
You don't need an implementation file. Just define all the required members inline (and don't define the pure virtual ones if you don't need to).
class Magic { public: Magic(void) {}; ~Magic(void) {}; virtual void display()=0; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With