Is a class constructor returning a class type reference or just a piece of memory?

As far as I know, the constructor does not have a return type. But in the next code snippet, it looks like ctor really returns a const reference object (does ctor have a return type const reference aclass that is hidden?), (Or) returns a piece of memory of type const reference (Q1)? or is it something else (Q1)? Are these objects valid that are returned by ctor (Q2), are they equivalent 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
+1
source share
1 answer

As you have determined, the constructor returns nothing; It does not have a return type.

In bits of your code that do things like this:

const c &co = c(3);

:

c(3) - c.

. /. ++ .

+2

Source: https://habr.com/ru/post/1534507/


All Articles