Noob constructor question
Hi, I am having a little trouble understanding constructiors and member functions. I am reading 2 books on c++, sams teach yourself c++ in 21 days and c++ interactive course. I am up to the chapter on constructors and both books take a different approach to using them. In the second book the member functions are in the class
example
Code:
class dog
{
private:
int d;
public:
int bark()
{
std::cout<<"Woof";
}
};
and in the first book they just call the function which is outside the class
Code:
class dog
{
private:
int d;
public:
int bark();
};
int bark()
{
std::cout<<"Woof";
}
does it make a difference?, which one is the usual way or doesn't it matter?
Also, with constructors, do you type its body within the class or outside of it?
I'm not quite sure if i understand constructors, are they just for defing the classes variables when an object is created and the deconstuctors get rid of them when the object dies?
Any help with this would be appreciated
Thanks:)
Re: Noob constructor question
Well, the second example should be
Code:
class dog
{
private:
int d;
public:
int bark();
};
int dog::bark()
{
std::cout<<"Woof";
}
The two ways are virtually identical (the only difference being that the first one acts as if its functions were declared with the inline keyword), but the second is usually preferred. This is because typically, a class is split into its interface (usually put in a .h file) and implementation (usually in a .cpp file).
Note that in both cases, the functions are a part of the class. In the first case, the function definition is inside the class definition. In the second case, the function is declared in the class definition, but is defined elsewhere.
Constructors and member functions can be defined within the class definition, or outside of it. It doesn't truly matter.