navig8tr
navig8tr

Reputation: 1844

C++ Does an abstract class without any data fields need a constructor?

Does an abstract class without any data fields need a constructor?

Also, since the implementation of the makeAMove function is in the derived classes, is it necessary to create a separate implementation file for this Player class or is a this single .h file alright?

#pragma once // include guard
#include "Board.h"

class Player
{
    public:
        virtual void makeAMove(Board &myBoard) = 0; // pure virtual function
};

Upvotes: 0

Views: 261

Answers (2)

Manu343726
Manu343726

Reputation: 14174

Yes, if the purpose of the abstract class is to provide polymorphic functionality through virtual funcions, that is, the class is an interface.

The base class should have a virtual dtor to ensure the correct destruction of polymorphic instances.

A good rule is: Every time a class hierarchy is dessigned to provide polymorphic functionality through dynamic binding, its base class should have a virtual dtor.

About classes and headers, C++ does not restrict you to write one class per file (as Java does).

What is more correct, to write one class per file or more than one classes? Depends, I think this is subjective. But in general C and C++ uses headers to provide functionality, and functionality commonly implies more than one class.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477100

Every class has a constructor, probably more than one. However, you don't always need to declare or define a constructor yourself, since under favourable conditions this happens implicitly. Such is the case in your example.

You also don't need an implementation file, since that would not contain anything.

Upvotes: 3

Related Questions