user9822022
user9822022

Reputation:

Initialization of the constant parameters of a constructor

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

Answers (1)

code_fodder
code_fodder

Reputation: 16411

You have a few issues here:

  1. As Remy pointed out you are missing a bracket
  2. You have your parameter names the same as your member names - this causes ambiguity (at least to the code writer) and this is why you have to use this->. One fairly standard way to get around this is to have your members start with m_, but there are other schemes.
  3. By using char* you will need to create dynamic memory and manage this, which is a pain, as others pointed out, use std::string.

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

Related Questions