Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to have a .cpp file for an abstract class?

Tags:

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?

like image 548
PeakGen Avatar asked Dec 22 '12 08:12

PeakGen


People also ask

Is an abstract class cpp?

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.

Are cpp files necessary?

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.

What is required for a class to be abstract?

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.

Should abstract classes have constructors C++?

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.


1 Answers

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; }; 
like image 97
Mat Avatar answered Sep 17 '22 17:09

Mat