0
Why do use pointers in C++ polymorphism?
I hate pointers, they're everywhere. Why in C++ polymorphism do we need to use pointers. So: class Enemy{ public: void attack(){ } }; class Ninja: public Enemy{ public: void attack(){ } } Ninja n; Enemy *enemy1 = &n; // I don't get this! Why do we need pointers at the end?! I don't get this at all. What does assigning object-pointer-thing "*enemy1" to address of object "n" even do? Is it necessary? What on earth does it do?!
7 Respostas
+ 1
Da2 I know what & is. It's a memory address. Throughout the entire course I have wondered what the point of pointers are. I still don't get it.
+ 1
Da2 Ok. I saw something in Stackoverflow. The best answer was along the lines of:
class Base {}
class Derived: Public base {}
Derived x;
Base y = x;
//is equivalent to:
Derived x;
Base *y = &x;
Is this somewhat correct would you say, this is the only example I've actually understood.
+ 1
Hello!
First of all polymorphism requires a pointer of mother class type to work because this is how it is designed, essentially you use different types (derived) trough a single type (base) , then it behaves accordingly to the derived class .
What's the point? OOP.
Polymorphism is a typical OOP feature and in C++ you use pointers, that's all.
The example provided in the lessons is just as simple as it can for the purpose of showing how it works.
In real life it is not used so much because it is really hard to handle.
Last..
Base y = x; is not equivalent, is a copy constructor call. It all depends on how you implemented the copy constructor for class Base
0
Pointers is use primarily to pass parameters. Understand memory address & you will begin to make some sense of pointers
0
A memory address contains a value (data). So if I need to use the same data with another function, I need to know the address😕
0
In a real world example, your house has an address which acts as a pointer so that other people will know how to get to you.
0
Forget about coding, focus on the concept