Reputation: 1728
I am trying to set an array of base class and derived classes in another class. For example, I have base class:
class Base{
public:
Base() {};
Base(float kv) : param(kv) {}
~Base() {};
float getParam() { return param; }
void setParam(bool kv) { param= kv; }
protected:
float param;
};
and derived classes like:
class Derived1: public Base{
public:
Derived1() {};
Derived1(float kv) : Base(kv) {}
~Derived1() {};
};
Now, in another class I have an array of Base type.
class Hive{
public:
Hive() {};
Hive(...) : ... {}
~Hive() {};
...
float getSomethingFromArray();
...
void setB();
protected:
...
Base *b[7];
};
Now, setB()
instantiate array, like:
b[0] = new Derived1();
but when I try to access method of b[0] it would't work. when I call method like:
b[0].setParam(i);
Compiler reports this error
IntelliSense: expression must have class type c:\users\miller\documents\visual studio 2010\projects\hello\hello\objekat.h 139 2 hello
Upvotes: 1
Views: 307
Reputation: 24412
Your mistake is very simple, to call method via pointer you must use ->
operator - not dot .
:
Not this way:
b[0].setParam(i);
But in this way:
b[0]->setParam(i);
Upvotes: 1
Reputation: 258618
but when I try to access method of b[0] it would't work. Any ideas why?
b[0]
is a Base*
. The compiler doesn't know whether the actual type of the object it points to is Base
, Derived1
or Derived42
, that's why it will only let you call methods from Base
on it - because those are the only ones that it can guarantee exist.
I'm guessing you're trying to call methods from Derived1
on it:
b[0] = new Derived1();
//...
b[0]->getSomethingFromArray();
but note that your code could easily be replaced by:
b[0] = new Base();
//...
b[0]->getSomethingFromArray();
what now? To get this to work, you can use casts and cast b[0]
to the type you need (provided you're sure of it). If your classes are polymorphic, you can use dynamic_cast
, which also does checks to make sure you're casting to the right type (research this).
Or, you could simply take advantage of polymorphism (only if it makes sense in your particular case).
Upvotes: 5