Question about classes (Need a quick response, please).

I just thought of something about classes when I looked back on working with them.

Can the private data members in a class be left uninitialized when the default constructor is called, or must they be initialized?

I am trying to do array of objects with a class (define in a header file, and the constructor in an implementation file).

NOTE: This has nothing to do with vectors, so keep talk of vectors out of this.
Last edited on
It would be much faster for you to actually try than ask..
Compile this:
1
2
3
4
5
6
7
8
9
10
class C{
private:
    int i;//private member
public:
    C(){}//a default constructor that doesn't initialize anything
};

int main(){
    return 0;
};


Keywords private, protected, public are called access specifiers. They specify access rights. They do nothing more.
I think you didn't read the part where I said:

"defined in a header file and the constructor in an implementation file."

-good sir.
I'm not sure why you are saying that it's defined in a header file and implemented in another file...it doesn't matter where you implement it.

Anyway, it's always good practice to initialize your member variables in the default constructor, that's why it's there.
Last edited on
header file:

1
2
3
4
5
6
class C{
private:
    int i;//private member
public:
  C();
};



Implementation
1
2
3
4
5
6
7
8
#include "header.hpp"
C::C()
{
};

int main(){
    return 0;
};


When you compile your code, the header file is copied and pasted into the place where it is included before the compiler even gets to look at it. No only does it make no difference - the compiler literally cannot tell that the header file is a separate file.

Topic archived. No new replies allowed.