Class inheritance and polyphormism

hi all,
i'm pretty new to this forum... in writing my degree thesis i'm getting a strange error (maybe cause i'm too much used to Java code).
Simply i need a class (A) to act as an interface or an abstract class, and various classes (B in this example) to inherit from the first one and
redefine a method. Later i want to make a new object of B type and store it in a A's array (arr).

The problem comes when i invoke the "method1()". I would like to invoke always child method, not the parent's one.
In the follow code, b.method1() in setup() function acts as i want, but arr[0].method1() in loop() function not.

I'm getting mad with this error since 2 nights ago :frowning:
Helppp!! :slight_smile:

class A {
  public:
    virtual ~A(){};
    virtual void method1() {Serial.begin(9600); Serial.println("Wrong method"); Serial.end(); }
};

class B : public A {
  public:
    virtual  ~B()  {};
    virtual void method1() { Serial.begin(9600); Serial.println("Right Method"); Serial.end(); }
};

A arr[1];

void setup() {
  A b = B();
  b.method1();
  arr[0] = b;
}

void loop() {
  arr[0].method1();
  delay(3000);  
}

Hi,
To me it looks like your problem is here -

A b = B();

and here

arr[0] = b;

This is saying something like, make the object of type A which is stored in b equal to a temporary instance of class B, which it is doing. When you then call your method, its still and object of type A which is what you asked to create, you just initialised it with a temporary B.

If you are trying to use polymorphism, fist of all, do you really need to ? and secondly if you really need to, use an array of pointers not object instances, for example

A *pMyObjects[2];

A myObjectOfTypeA;
B myObjectOfTypeB;

pMyObjects[0] = &myObjectOfTypeA;
pMyObjects[1] = &myObjectOfTypeB;

Note: My C++ is rusty so syntax might be a little off.

Calling the method on these two should give the results you expect, but unless you are dynamically creating your objects, it might be complexity for the sake of it - and thats still valid thesis content ie. one approach would be polymorphism ... however on further analysis ....

Duane B

rcarduino.blogspot.com

The following C++ statement

A b;

doesn't mean "b is an object of type A", but rather "b is an instance of A" (i.e. an object).

Compare those two lines:

Class obj = new Class();    // java
Class* obj = new Class();   // C++

I re-wrote something similar to your example with pointers:

class A {
    public:
    virtual void f() { Serial.println("A"); }
};

class B : public A {
    public:
    virtual void f() { Serial.println("B"); }
};


void setup() {
    A* obj;    // base-class pointer

    Serial.begin(115200);

    obj = new A();
    obj->f();         // base class version
    obj = new B();
    obj->f();        // child class version
}

void loop() {
}

The serial monitor shows
A
B

Thank you so much!

this is really what is was looking for!!!