1

Below is my .h file

#include <iostream>
#include <string>

using namespace std;

class ClassTwo
{
private:
string sType;
int x,y;
public:
void setSType(string);
void setX(int);
void setY(int);

string getSType();
int getX();
int getY();
};

I want to construct 2 Constructor.

which constructor 1 will be no parameter, initialize all int value as 0 and string as empty string.

Constructor 2 will be taking in parameter which is sType, x and y using method get set.

but how do i achieve this. should i code this in my cpp file or .h file

roalz
  • 2,699
  • 3
  • 25
  • 42
  • See [What is the member variables list after the colon in a constructor good for?](http://stackoverflow.com/questions/210616/what-is-the-member-variables-list-after-the-colon-in-a-constructor-good-for?lq=1) – Bo Persson Oct 07 '12 at 09:26

2 Answers2

1

For the default constructor:

ClassTwo() : sType(), x(), y() {}

You can choose to be more explicit with the initialization for clarity:

ClassTwo() : sType(""), x(0), y(0) {}

You can also omit the initialization of the string, its default is "".

For the second constructor, it is best implemented without the setters:

ClassTwo(const std::string& s, int x, int y) : sType(s), x(x), y(y) {}

Whether you implement in the header or the .cpp is up to you. I see no disadvantage from implementing such simple constructors in the header.

I suggest you use a naming convention for data members. Names such as x and y are likely to result in clashes elsewhere in your code.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

The header is for definitions. Code that includes a header doesn't have to know any implementation (unless you're using templates which is a different story...)

Anyway, 2 constructors:

public:
ClassTwo() : sType(""), x(0), y(0) {}
ClassTwo(string _type) : sType(_type), x(0), y(0) {}
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185