ralston3 ralston3 - 1 month ago 7
C++ Question

Accessing constructor parameters in class method

I'm coming from Python and trying to get started with C++, but I seem to be unable to figure out how to access class parameters in C++. I've attached a example Python class, as well as my 3 C++ files.

If this is the Python:

class Greeting:
def __init__(self, name):
self.name = name
def say_name(self):
return "Hello, %s" % self.name


What would be the C++ equivalent of accessing the
self.name
instance param in the
say_name
method?

Right now this is what I have:

greeting.hpp

class greeting
{

public:

greeting(std::string name);
~greeting();

std::string salutation(std::string salutation);

private:

// Nothing

};


greeting.cpp

#include "greeting.hpp"

greeting::greeting(std::string name, std::string nationality)
{
std::cout << "greeting class constructed\n";

}

greeting::~greeting()
{

}

std::string greeting::salutation(std::string salutation)
{
std::string res = salutation + ", " + name;
return res;
}


main.cpp

#include <iostream>
#include "greeting.hpp"

int main(int argc, const char * argv[]) {

greeting obj = greeting("Rashad", "American");

std::string word = "Hello";

std::cout << obj.salutation(word) << std::endl;

return 0;
}


Obviously this won't run because the
name
param in the
greeting::salutation
method can't be accessed. So can someone explain how/if I can access C++ constructor params in class methods (similar to the above Python example)?

I'm Running C++ on XCode 8. Thanks

Answer

In your python code, you have:

    self.name = name

The object has a member variable called name which stores the given input. You need something similar in the C++ class.

class greeting
{
  public:

    greeting(std::string name);
    ~greeting();

    std::string salutation(std::string salutation);

 private:

    // Add name as a private member
    std::string name_;

};

and make sure the name is stored in the member variable in the constructor.

greeting::greeting(std::string name) : name_(name)
{
   std::cout << "greeting class constructed\n";
}

You can use the member variable name_ in other member functions.

std::string greeting::salutation(std::string salutation)
{
    std::string res = salutation + ", " + name_;
    return res;
}