D
D
Dima Gashko2018-12-24 00:08:37
OOP
Dima Gashko, 2018-12-24 00:08:37

How to properly define attributes when inheriting (c++, OOP)?

I have a defined class hierarchy.
I need to make it possible to pass through some objects and not through others.
I think that for this I need to add an attribute of the type to the base class:
bool obstacle = false;
And also the method:
bool isObstacle() {return obstacle}
After that, for example in Wall write:
bool obstacle = true;
But in this form it does not work. The isObstacle method still returns the value from the base class.
How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-12-24
@vt4a2h

You can do it like this for example:

#include <iostream>
#include <iomanip>
#include <memory>

class ISomeInterface
{
public:
  virtual bool isFoo() const noexcept = 0;
};

class Foo : public ISomeInterface
{
public: 
  bool isFoo() const noexcept override { return true; }
};

class Bar : public ISomeInterface
{
public: 
  bool isFoo() const noexcept override { return false; }
};

int main()
{
  // Or shared_ptr/make_shared
  std::unique_ptr<ISomeInterface> foo = std::make_unique<Foo>();
  std::cout << "Foo is Foo: " << std::boolalpha << foo->isFoo() << std::endl;
  
  // Or shared_ptr/make_shared
  std::unique_ptr<ISomeInterface> bar = std::make_unique<Bar>();
  std::cout << "Bar is Foo: " << std::boolalpha << bar->isFoo() << std::endl;
  
  return 0;
}

Well, in the methods it is not necessary to return just true / false, there can be any other variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question