Prashant Gupta
Prashant Gupta

Reputation: 113

C++ passing pointer reference

I want to pass pointer object to function by reference. I don't know If I am doing correct as It is not working as per below code. Please help me.

class Base
{
    public:  
    int x;
    void print()// function prints x value
    {
        cout<<x;
    }
    void call_print(Base **base) //function call print function
    {
        base->print();
    }
};
int main()
{
    Base *b = new Base; // creating pointer object
    b->call_print(&b); // passing pointer by reference
    return 0;
}

Upvotes: 2

Views: 2051

Answers (3)

Prashant Gupta
Prashant Gupta

Reputation: 113

#include <iostream>
using namespace std;
class Base
{
    public:  
    int x;
    void print()
    {
        cout<<x<<endl;
    }
};
class Base2
{
    public:
    void change_value(Base *&base) 
    {
        base->x = 5;
    }
};
int main()
{
    Base *b = new Base;
    Base2 b2;
    b2.change_value(b);
    b->print();
    delete b;
    return 0;
}

Upvotes: -1

madduci
madduci

Reputation: 2883

a simple note: don't use naked pointers, take advantage of C++11 facilities: std::unique_ptr and std::shared_ptr are even better, for resource management sake, and you can write something like this:

std::unique_ptr<Base> base_ptr(new Base());
base_ptr->call_print();
//no delete, unique_ptr deletes itself automatically

and for Base class, you have to write:

void call_print() //function call print function
{
    this->print();
}

because you don't need to pass to the same object, the reference to itself.

Upvotes: 0

David G
David G

Reputation: 96790

You're passing the object by "reference" in the sense that you still have access to the original object through the parameter, but note that base in call_print() is a pointer to the object being passed in, not the actual object. You still have to dereference the pointer if you want access to the object passed in:

(*base)->print();

C++ introduced actual references that are syntactic sugar upon what you have to do with pointers/double-pointers. For example:

void call_print(Base*& base)
{ base->print(); }

b->call_print(b);

Also, the use of a double pointer or reference seems unnecessary since you don't need to modify the pointer in any way. Why not just take in the pointer itself?

void call_print(Base* base)
{ base->print(); }

b->call_print(b);

And lastly, you don't need to pass b in as an argument to its own method. A pointer to the Base object is accessible through this:

void call_print()
{
    print(); /* or this->print() */
}

b->call_print();

Upvotes: 5

Related Questions