Reputation:
class TrainRoute
{
private:
string departure;
string destination;
char* trainCode;
public:
TrainRoute()
{
departure = "";
destination = "";
trainCode = nullptr;
}
TrainRoute(string departure, string destination, const char* trainCode : departure(departure),destination(destination)
{
this->departure = departure;
this->destination = destination;
}
The problem is when initializing the const char * trainCode parameter in the constructor other than nulptr
In what ways can I use this parameter?
Upvotes: 0
Views: 114
Reputation: 16411
You have a few issues here:
this->
. One fairly standard way to get around this is to have your members start with m_
, but there are other schemes.But if you must use char arrays then: live demo
#include <iostream>
#include <cstring>
using namespace std;
class TrainRoute
{
private:
string m_departure;
string m_destination;
char* m_trainCode;
public:
TrainRoute()
{
m_departure = "";
m_destination = "";
m_trainCode = nullptr;
}
TrainRoute(string departure, string destination, const char* trainCode)
: m_departure(departure)
, m_destination(destination)
{
m_trainCode = new char[strlen(trainCode)];
strcpy(m_trainCode, trainCode);
}
~TrainRoute()
{
// Most now free this mem
delete[] m_trainCode;
}
void print()
{
std::cout << "dept: " << m_departure << std::endl;
std::cout << "dest: " << m_destination << std::endl;
std::cout << "code: " << m_trainCode << std::endl;
}
};
int main()
{
TrainRoute tr("start", "dest", "code123");
tr.print();
return 0;
}
Note: here I have to create a new memory buffer to store the string into and copy the parameter string into it AND in the destructor make sure I free that memory... So by using std::string - you don't need any of that :)
Here is the same code, but using a string member to store the const char *
(assuming you must take a string as a parameter): using string - it also has a few other modern c++ improvements
Upvotes: 1