passing pointers in data slicing example

I know what & how pointers and references are used. At least I thought
I did. I came across this code that explains Data slicing by
passing by value, see below. My question concerns the three functions
that are within the while statement below, I will put it here for easier reference.


ptrfunction(ptr);
reffunction(*ptr);
valuefunction(*ptr);

I am confused as to what these functions are passing.
Here is my confusion. For example the valuefunction above accepts a pointer.
But why is it called valuefunction? Passing by value it should have been written as follows valuefunction(ptr) not valuefunction(*ptr). For the
ptrfunction(ptr) above why is it not ptrfunction(*ptr) and
reffunction(*ptr) should be reffunction(ptr).

Can someone explain why it is written in this manner?




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
64
65
66
67
68
69
70
71
72
73
74
75
76
  #include <iostream>
//data slicing with passing by value
   
using namespace std;
class mammal  
{
public:   
//constructors
mammal():itsage(1){}
virtual ~mammal(){}
virtual void speak() const{cout<<"mammal speak~\n";}
protected:
int itsage;
};
                
      
class Dog : public mammal
{
public:
void speak()const{cout<<"woof!\n";}
};                   
  
class Cat : public mammal
{
public:
void speak()const{cout<<"meow!\n";}
};     
             
void valuefunction(mammal);
void ptrfunction(mammal*);
void reffunction(mammal&);
                                                                 
int main()
{     
mammal* ptr=0;
int choice;
while(1)
{
bool fquit=false;
       

cout<<"(1)dog (2)cat (0)quit:";
cin>>choice;
switch (choice)
{
case 0: fquit=true;
break;
case 1: ptr=new Dog;
break;
case 2: ptr=new Cat;
break;
default: ptr=new mammal;
break;
}
if(fquit==true)
break;
ptrfunction(ptr); 
reffunction(*ptr);            
valuefunction(*ptr);
}

                
return 0;
}
void valuefunction (mammal mammalvalue)
{
mammalvalue.speak();
}
void ptrfunction(mammal *pmammal)
{
pmammal->speak();
}
void reffunction(mammal & rmammal)
{
rmammal.speak();
}
> Here is my confusion. For example the valuefunction above accepts a pointer.
No, it does not.
See the declaration of the function, it accepts an object.
void valuefunction(mammal);


> Can someone explain why it is written in this manner?
You seem to be confusing by the calls to the function.
If the function wants an object you must pass an object, the compiler will reject anything else.
There you've got a pointer. If you dereference a pointer (with operator *) you'll get an object, that's what you are passing to the fuction.


Also, indent your code.
Topic archived. No new replies allowed.