Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract/Base struct in C++?

I'm making a chess game and I would like to have an array of pieces.

If I'm correct, in Java you can have an abstract Piece class and have King or Queen extend that class. If I were to make an array of Pieces I could place a King piece somewhere in that array and a Queen piece at another spot because both King and Queen extend Piece.

Is there any way to do that with structures in C++?

like image 411
Austin Moore Avatar asked Jan 27 '12 06:01

Austin Moore


People also ask

What is abstract base class in C?

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. You declare a pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.

Can struct be abstract?

Since inheritance isn't supported for structs, the declared accessibility of a struct member cannot be protected , private protected , or protected internal . Function members in a struct cannot be abstract or virtual, and the override modifier is allowed only to override methods inherited from System. ValueType .

What is abstract base class with example?

Pure Virtual Functions and Abstract Classes in C++ Such a class is called abstract class. For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know every derived class must have implementation of draw().

What is a base abstract?

Abstract base classes separate the interface from the implementation. They define generic methods and properties that must be used in subclasses. Implementation is handled by the concrete subclasses where we can create objects that can handle tasks.


1 Answers

Yes. You can create an abstract base class in C++. Simply set one or more of the methods to be pure virtual:

class Piece {
    public:
        Piece ();
        virtual ~Piece ();
        virtual void SomeMethod () = 0;  // This method is not implemented in the base class, making it a pure virtual method. Subclasses must implement it
 };

You can then create sub-classes that implement the pure virtual methods

class King : public Piece {
    // ... the rest of the class definition
    virtual void SomeMethod (); // You need to actually implement this
};
like image 199
user1118321 Avatar answered Sep 27 '22 15:09

user1118321