Renuka
Renuka

Reputation: 217

Does the constructor of a class return a reference of the class type or just a piece of memory?

As far I know, constructor has no return type. But in the following piece of code it looks ctor does returns a const reference object(does ctor has a return type of const reference aclass, which is hidden?), (or) returns a piece of memory of type const reference(Q1)? or is this something else(Q1)? are these objects are valid which is returned by the ctor(Q2), are they equivalent to c stack_object; (Q2)? Please share your thoughts.

#include<iostream>
using namespace std;    

class c{
    public:
        int x = 88;
        c(int i){
            x=i; 
        //  cout<<"\nc1 ctor\n";
        }
        c(){
        //  cout<<"\nc ctor\n";
        }
        ~c(){
        //  cout<<"\nc dtor\n";
        }
};

int f(){
     const  c & co1 = c();  //ctor returns a const reference obj of type c class
     c &ref = const_cast<c&>(co1);  //casting away const
     cout<<"\n addr3 = "<<&ref<<"\n";  //another new address
     ref.x = 99;
     //cout<<ref.x;
}


int main(){
    const  c &co = c(3);   
    c *p = const_cast<c*>(&co);

    cout<<"\n addr1 = "<<p<<"\n";   
    //cout<<p->x;  //out puts 3      
    p->x = 11; //just assigning some new values

    const  c & co1 = c();
    c *p1 = const_cast<c*>(&co1);

    cout<<"\n addr2 = "<<p1<<"\n";  //new address
    //cout<<"\n"<<p1->x;

    f();

    cout<<"\n main() Done\n";
     return 0;
}

o/p here:

 addr1 = 0xbfc3c248

 addr2 = 0xbfc3c24c

 addr3 = 0xbfc3c214

 main() Done

Upvotes: 1

Views: 58

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

As you've identified, a constructor doesn't return anything; it doesn't have a return type.

In bits of your code that do things like this:

const c &co = c(3);

it is valid to say the following:

The expression c(3) is an rvalue of type c.

However, you're creating a temporary object, and binding a reference to it. Normally, the lifetime of a temporary ends at the end of that statement/sequence point. However, the C++ standard guarantees that its lifetime is prolonged.

Upvotes: 2

Related Questions