In one of my classes GUI I have a private variable for the class User u. In this GUI class I have a function for the user to login in then check if their account is admin or a normal user and then from that create either a User or Admin object. Admin is derived from user with a few more privileges. How do I set the private variable User u to be either an Admin object or User object after they login.
Asked
Active
Viewed 58 times
-2
Cj280
- 23
- 2
-
2Read about polymorphism in your favourite C++ book. – molbdnilo Apr 29 '17 at 14:33
1 Answers
-2
If the Admin class is extending the User class then you can use User u to represent both of them.
When you need only Admin and you don't know if u is an Admin or User object you can check it like this at runtime:
if(Admin * v = dynamic_cast<Admin*>(u)) {
// u was safely casted to Admin
v->doSomething();
}
N.B.
dynamic_cast is an operation with big cost you can read here some workarounds.
Community
- 1
- 1
granmirupa
- 2,780
- 16
- 27
-
I didn't vote, but the proposed solution won't lead to code with good / clean architecture. Sure, an admin "is a" user, but it's probably better to give different users different "roles". – Daniel Jour Apr 29 '17 at 15:23
-
1@DanielJour I'm not judging the architecture.. I'm answering to the request of the question. In the question is written *Admin is derived from user* – granmirupa Apr 29 '17 at 15:28