Home > Blockchain >  Will asigning a variable to another variable result in it using a copy constructor or being a refere
Will asigning a variable to another variable result in it using a copy constructor or being a refere

Time:12-09

I am a little confused with the copy constructor and references in c .

Kat kat("hello kitty");
Kat newKat = kat;

Will Kat use its copy constructor or will newKat just become a reference to Kat.

Edit: sorry for the confusion, I mean for custom types.

CodePudding user response:

Kat kat("hello kitty");
Kat newKat = kat;

Will use the copy constructor

Kat kat("hello kitty");
Kat& newKat = kat;

Will create a reference

CodePudding user response:

Since when creating the Kat object you don't use the new keyword and your variable is not a reference type (See more) (or pointer) the object is being created on the Stack. Assigning objects from the stack will result in them getting copied, so it will use the copy constructor.

CodePudding user response:

I think this can be a better answer to your question since you need to understand all of the special member functions and not just the copy constructor.

Now take a look at this:

#include <iostream>
#include <utility>
#include <string>


class Kat
{
public:
    Kat( )
    :msg( "Default Msg" )
    {
        std::clog << "default ctor" << '\n';
    }

    Kat( const std::string& message )
    : msg( message )
    {
        std::clog << "parameterized ctor" << '\n';
    }

    Kat( const Kat& rhs )                // copy ctor
    : msg( rhs.msg )
    {
        std::clog << "copy ctor" << '\n';
    }

    Kat& operator=( const Kat& rhs )     // copy assignment operator
    {
        if ( this != &rhs )
        {
            msg = rhs.msg;
        }

        std::clog << "copy assignment operator" << '\n';

        return *this;
    }

    Kat( Kat&& rhs ) noexcept            // move ctor
    : msg( rhs.msg )
    {
        rhs.msg = "";

        std::clog << "move ctor" << '\n';
    }

    Kat& operator=( Kat&& rhs ) noexcept // move assignment operator
    {
        if ( this != &rhs )
        {
            msg = rhs.msg;

            rhs.msg = "";
        }

        std::clog << "move assignment operator" << '\n';

        return *this;
    }

private:
    std::string msg;
};

int main( )
{
    Kat kat1; // default ctor
    Kat kat2( "hello kitty" ); // parameterized ctor

    Kat kat3 = kat2; // copy ctor
    Kat kat4( kat2 ); // also copy ctor

    kat1 = kat2; // copy assignment operator

    Kat kat5 = std::move( kat2 ); // move ctor
    Kat kat6( std::move( kat3 ) ); // also move ctor

    kat6 = std::move( kat1 ); // move assignment operator

    return 0;
}

And the output:

default ctor
parameterized ctor
copy ctor
copy ctor
copy assignment operator
move ctor
move ctor
move assignment operator
  •  Tags:  
  • c
  • Related