C++ Code issue

Hi All

I am stuck with the below C++ Compiler errors.
Any suggestions?

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
#include <iostream>

using namespace std;

class XXX{
    public:
    int memberFunc();
};

class YYY: public XXX{
    public:
    int memberFunc();
};

int main()
{
    //cout<<"Hello World";

    //return 0;
    XXX *bptr = new YYY;
    YYY  *dptr;
    //dptr = static_cast<YYY*>(bptr);
    dptr = up_cast<XXX*>(bptr);
}



output: 

Compilation failed due to following error(s).main.cpp:31:12: error: ‘up_cast’ was not declared in this scope
   31 |     dptr = up_cast<XXX*>(bptr);
      |            ^~~~~~~
main.cpp:31:23: error: expected primary-expression before ‘*’ token
   31 |     dptr = up_cast<XXX*>(bptr);
      |                       ^
main.cpp:31:24: error: expected primary-expression before ‘>’ token
   31 |     dptr = up_cast<XXX*>(bptr);
      |                        ^
either up+cast is no such thing that you need to define and provide, or its a c++20 thing I haven't checked out and you need to enable c++20 in your compiler flags so it uses the new standard, or something of this nature. the compiler does not understand up_cast.
I use C++ 11 HERE and not C++ 20.
So, where is the definition of up_cast?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class XXX{
    public:
    void memberFunc(){ cout << "Base member function\n"; }
};

class YYY: public XXX{
    public:
    void memberFunc(){ cout << "Derived member function\n"; }
};

int main()
{
    XXX *bptr = new YYY;
    YYY  *dptr;
    dptr = (YYY*)(bptr);
    bptr->memberFunc();
    dptr->memberFunc();
}

Hi lastchance

Do you mean up_cast is not required here?
What is "up_cast<>"? It certainly isn't a C++ standard operator/function.

Are you trying to upcast and downcast between a base and derived class?

https://www.bogotobogo.com/cplusplus/upcasting_downcasting.php
If i modified my code as below, it still gives compile errors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class XXX { 
    public: 
        int memberFunc();
};
 
class YYY : public XXX { 
    int memberFunc();
};
 
int main()
{
    XXX * bptr = new YYY ; 
    YYY * dptr;
 
    dptr = dynamic_cast<YYY*>(bptr);
}

Output:
15:35: error: cannot dynamic_cast ‘bptr’ (of type ‘class XXX*’) to type ‘class YYY*’ (source type is not polymorphic)
Make XXX::memberFunc() virtual so that XXX and YYY are then polymorphic as per the hint in the error message.
Add the line
virtual ~XXX() = default;
in the class XXX declaration. It should have a virtual destructor anyway.
Topic archived. No new replies allowed.