0

Here are the program details, below I have proved my concern using the comment symbol(//)

#include <iostream>

using namespace std;

class Pet {
protected:
string name;
public:
Pet(){}
Pet(string name)
{ 
    this -> name = name; 
}
void make_sound()
{ 
    cout << name << " says: no comments" << endl; 
}
};
void name_pet_by_value(string name, Pet pet)
{
 //pet.name->name; // how to call Pet() constructor here?
}

void play_with_pet_by_pointer(string name, Pet *pet)
{
pet = new Pet(name);  // how to call Pet() constructor here? , is it the right way?
pet -> make_sound();
}

void play_with_pet_by_reference(string name, Pet pet)
{
 pet.Pet(name);
 pet.make_sound(); // Same concern here also and why we call this way
}

int main()
 {
  Pet *p1  = new Pet();
  Pet  p2;

  play_with_pet_by_pointer("anonymous", p1);
  play_with_pet_by_reference("no_name", p2);
  play_with_pet_by_pointer("no_name", &p2);
  play_with_pet_by_reference("anonymous", *p1);
  name_pet_by_value("Alpha", pet);
  pet.make_sound();
  return 0;

}

If the above program is not right please check, my concern is how to call Pet()(constructor) after passing the object as function argument.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
BUBAI NAYAK
  • 49
  • 1
  • 9
  • Constructors do not have names in C++. Moreover, they cannot be explicitly called. – Jason Jun 03 '22 at 17:21
  • Constructors are used to create class objects. You can't call a constructor "for" an object that already exists. – aschepler Jun 03 '22 at 17:23
  • You are asking some very basic questions, and stackoverflow is not an effective way to start learning a programming language. I suggest reading [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – aschepler Jun 03 '22 at 17:25

0 Answers0