Click here to Skip to main content
15,917,795 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a message. Passing the message as a reference to a function. Within the function, passing the message to other function that taking the message as a value. Program is running fine and giving the expected output. Is there any issue to do like this?

Example:

C++
#include <iostream>
#include <string>

void displayMessage(std::string str) //taking parameter as a value
{
    std::cout<<str<<std::endl;
}
 
void showmessage(std::string &str) //taking parameter as a reference
{
   std::cout<<str<<std::endl;
 
   displaymessage(str);
}


int main()
{
   std::string str="Hello" ;
   showmessage(str);
   return 0;
}


What I have tried:

I have a message. Passing the message as a reference to a function. Within the function, passing the message to other function that taking the message as a value.
Posted
Updated 25-Dec-21 17:09pm
v3

1 solution

There are no issues with your code. When you call dislplaymessage() from within showmessage(), a copy of the object referenced by shomessage() argument str is created, nota copy of the reference. This can be demonstrated simply:
C++
#include <iostream>

class C
{
public:
    // constructor
    C(){ 
        std::cout << "constructor\n";
    }

    // copy constructor
    C(const C &other) {
        std::cout << "copy constructor\n";
    }
};


void foo(C c)
{
    std::cout << "foo\n";
}

void bar(C& c)
{
    std::cout << "bar\n";
    foo(c);
}

int main()
{
    C c;

    bar(c);
}

produces the output
constructor
bar
copy constructor
foo
 
Share this answer
 
Comments
Member 14036158 26-Dec-21 0:22am    
Thanks for the explanation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900