PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 17, 2022

[FIXED] how to initialize a class object reference in C++ to simulate NRVO?

 December 17, 2022     c++, syntax     No comments   

Issue

I meet a course programming problem, which asks me to initialize the A a using passing by reference (initialize the A a in the func). How can I call A's constructor by A's reference?

#include <iostream>
using namespace std;

class A
{
public:
    int x;
    A()
    {
        cout << "default constructor" << endl;
        x = 1;
    }

    A(int x)
    {   
        cout << "constructor with param = "  << x << endl;
        this->x = x;
    }

    ~A() {
        cout << "destructor" << endl;
    }

    void print() {
        cout << x << endl;
    }
};


void fun(A& a)
{
    a.A::A(10); // error!
    return;
}


int main()
{
    A a; 
    fun(a);
    a.print();
    return EXIT_SUCCESS;
}

There is a background of this problem. The teacher want us to replicate the NRVO(named return value optimization) result.

#include <iostream>
using namespace std;

class A
{
public:
    int x;
    A()
    {
        cout << "default constructor" << endl;
        x = 1;
    }

    A(int x)
    {   
        cout << "constructor with param = "  << x << endl;
        this->x = x;
    }

    ~A() {
        cout << "destructor" << endl;
    }

    void print() {
        cout << x << endl;
    }
};

A fun() {
    A a = A(10);
    return a;
}


int main()
{
    A a = fun();
    return EXIT_SUCCESS;
}

default g++ compiler:

constructor with param = 10
destructor

if we close the NRVO: g++ test.cpp -fno-elide-constructors

constructor with param = 10
destructor
destructor
destructor
destructor

The teacher want us to replicate the NRVO(named return value optimization) result by passing by reference.


Solution

The syntax a.A::A(10); is incorrect.

Constructor is used to create an object of a class, you cannot call it on an already existing object. Even a constructor cannot be explicitly called. It is implicitly called by the compiler.

From general-1.sentence-2:

Constructors do not have names.

Thus, you cannot call a constructor explicitly. The compiler will automatically call the constructor when an object of that class-type is created.



Answered By - Jason Liam
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing