Return derived class reference!

Hi,
I am having a little trouble to get the reference of a derived class. For example -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class A
{
public:
   A() {}
   virtual ~A() {}
   
   virtual void func()
   {
      // something
   }
};

class B : public A
{
public:
   B():A() {}
   virtual ~B() {}

   void func()
   {
      // something
   }

   void func2()
   {
      // something else
   }
};

class C
{
public:
   C() {}
   ~C() {}

   B& getB()
   {
      return _derived;
   }

private:
   B _derived;
};

Suppose I have something like this, now If I call like -
1
2
C _caller;
_caller.getB().func2();

I get error: func2 is not a member of A. How to solve it?

EDIT:
Making the getB a pointer and dynamic_cast solved the problem.
1
2
3
4
B* getB()
{
   return &_derived;
}


Thanks in advance.
Last edited on
you should put your method for a and b public .
also b constructor does not call a constructor.

try that , then if it does not work , tell us.
Sorry, those are public, I forgot to wrote that. Edited the first post. As I said - Making the getB() a pointer and dynamic_cast solved the problem, like -
1
2
3
4
B* getB()
{
   return &_derived;
}

And than -
1
2
C* _caller = new C;
B* _derived = dynamic_cast<B*>(_caller->getB());

Is this OK?

Thank you.
Does this fit your intention?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class A
{
public:
   A() {}
   virtual ~A() {}
   
   virtual void func()
   {
      // something
   }
};

class B : public A
{
public:
   B():A() {}
   virtual ~B() {}

   void func()
   {
       // something
   }

   void func2()
   {
       // something else
   }
};

class C
{
public:
   C() {}
   ~C() {}

   A& getB()
   {
       return _derived;
   }

private:
   B _derived;
};

int main(int argc, const char * argv[])
{
    int exit_status = EXIT_SUCCESS;

    C _caller;

    try
    {
        dynamic_cast<B &>(_caller.getB()).func2();
    }
    catch (const std::bad_cast &)
    {
        std::cerr << "Bad cast" << std::endl;
        exit_status = EXIT_FAILURE;
    }

    return exit_status;

} /* main() */


But be careful! (http://www.cplusplus.com/reference/typeinfo/bad_cast/)
Yes, it also works. Thanks for the reply.
Topic archived. No new replies allowed.