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 Piece
s 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++?
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.
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 .
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().
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.
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
};
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