Pointers

trying to make a pointer which call function from human class but having difficulties please check below on line number 28-29

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
  #include<iostream>
using namespace std;

class human
{
public:
	void fun()
	{
		cout << "Human\n";
	}
};
class man : public human
{
public:
	void fun()
	{
		cout << "Man\n";
	}
};

void main()
{
	human h1;
	man m1;
	h1.fun();
	m1.fun();

	human* ptr;
	ptr->&fun();
}
ptr->&fun(); should be ptr->fun();

But you didn't make that pointer point to anything.
You need to make that pointer point to something.

human *ptr = &h1;
or
human *ptr = &m1;
will both work, but what do you think will happen if you do
1
2
human *ptr = &m1;
ptr->fun();

Which "fun" will be called?
human* ptr creates a pointer to a human (or derived type), but does not create an instance of a human (or derived type). You will need to can call the objects constructor like so:
1
2
3
human* ptr = new human();
// OR
human* ptr = new man();


Additionally, you will need to make the fun() method virtual so that the derived class can override it.

To call the function you should just use ptr->fun();
Last edited on
No, you don't need to create a new one. You can have the pointer point to an instance that already exists, like in the code I showed above.

You CAN (and then of course make you to delete it), but to use a pointer you can make a new one or make it point to an instance of that class you created earlier (which then of course you don't call delete on).
Last edited on
Topic archived. No new replies allowed.