0

I want to have a class that I can inherit from and overwrite the function that creates the value for the [] operator. Why do these not have the same result? Is there a way to get the second result without using a pointer?

Code:

#include <iostream>

using std::cout;

class session {
  public:
    session(){}
    ~session(){}
    void operator[](const char* c) {foo(c);}

  protected:
    virtual void foo(const char* c) {cout << "parent called" << "\n";}
};

class session2 : public session {
  public:
    session2(){}
    ~session2(){}

  protected:
    virtual void foo(const char* c) {cout << c << "\n";}
};

int main() {
  session2 s2;

  session a = s2;
  a["child called"];

  session* b = &s2;
  (*b)["child called"];

  return 0;
}

Output:

parent called
child called
Alden
  • 2,229
  • 1
  • 15
  • 21

2 Answers2

1
session a = s2;

This means "Make a new session object, and initialize it from the value of s2." Note that a is a session object, it is not a session2 object. Therefore, it's virtual methods will use the "parent"'s definitions. Runtime polymorphism therefore only works through references and pointers, which do not create new objects. They simply refer to existing objects.

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
1

If you don't want to use a pointer then use a reference.

session2 s2;

session& a = s2;

If you don't use a pointer or reference, there will be slicing going on and everything special about the derived object will be lost. Only the parts from the parent will be left.

Read more about slicing here: What is object slicing?

Community
  • 1
  • 1
Felix Glas
  • 15,065
  • 7
  • 53
  • 82