-3

I am trying to set this char* to NULL using a default constructor. But I am facing trouble. The problem is with the line where I am using a default constructor and setting m_name=NULL;

class Car {
    char *m_name;
    int m_carnum;
public:
    Car() :m_carnum(0), m_name = NULL {} //this line has the error
    ~Car(){}
};

While this code seems to be working:

Car() :m_carnum(0) {
    m_name = NULL;
}

So I why isn't this working ?

m_name = NULL;

Isan Rivkin
  • 177
  • 1
  • 15
  • If you have a problem, **EXPLAIN YOUR PROBLEM**. And read [ask] – Amit Mar 13 '16 at 20:06
  • You say `m_name = NULL;` is working. You then ask why `m_name = NULL;` isn't working. That doesn't make sense. You don't have `m_name = NULL;` in your non-working version, you just have `m_name = NULL`. Not that it would work if you inserted a semicolon there, but it's important to be precise. The compiler is, and if you're not, you're sure to get a lot of other problems in the future. –  Mar 13 '16 at 20:11

2 Answers2

1

Instantiate it like your int. You also need to make sure you instantiate member variables in the order they are declared (see Why should I initialize member variables in the order they're declared in?)

Car() : m_name(0), m_carnum(0) 
{}
Community
  • 1
  • 1
Ryan
  • 1,797
  • 12
  • 19
  • 1
    Nice answer. But some explanation on this advice `make sure you instantiate member variables in the order they are declared` would be nice. – HolyBlackCat Mar 13 '16 at 20:08
1

Given that you are dealing with a pointer, the following might be advisable (considered good practise) if using C++ 11 and beyond:

Car() : m_name(nullptr), m_carnum(0) {}

The reasoning behind this is outlined here (among other places with a quick search): What are the advantages of using nullptr?

Community
  • 1
  • 1
berilac
  • 48
  • 1
  • 7