passing argument through constructor

Hey guys,

A simple question, I want to initialize my variables in a class using a constructor. the data will be taken from the user, stored in local variable in MAIN and it should be passed to constructor, by when doing it in action, its wrong, is there any special form here for giving argument to the constructor?

thanks
You just declare the arguments in the constructor declaration and definition, just like you would for any other method that takes arguments.
I did, ok mikey let me write you part of the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

class mikey{
public:
mikey(int x, int y){x1=x; y1=y;}
private:
int x1, int y1;
}

int main()
{
int M_x, M_y;
cin>>M_x;
cin>>M_y;
mikey m1(M_x, M_y);
}


it does not work cause i have declared two argument of type int to be passed to the argument, so my question is how the variable values in main should be passed now to the constructor?
Hi there

It does work: http://coliru.stacked-crooked.com/a/96c7a4ece773ba1b
I merely cleaned up your code a little.

The constructor arguments are ints, and the variables in main are ints, so it will work - why did you think it wouldn't work?

All the best,
NwN
NwN, thanks for your reply, because when i run the code, compiler returns an error stating that this function has not been declared, but when i replace those variables with actual integers there will be no problem.

regards
The only obvious mistake I can see is that you don't have a semicolon at the end of your class definition. It should be:

1
2
3
4
5
6
class mikey{
public:
mikey(int x, int y){x1=x; y1=y;}
private:
int x1, int y1;
}; // <<<<< Semicolon here. 


EDIT: And it's better to use an initialiser list in your constructor, instead of assigning values within the body of the constructor:

1
2
3
4
5
6
7
8
9
10
11
class mikey{
public:
  mikey(int x, int y)
  : x1(x)
  , y1(y)
  {}

private:
  int x1, int y1;
}; // <<<<< Semicolon here.


Plus your code is easier to read if you adopt a sensible indentation policy?
Last edited on
mikeyboy was right, your code is valid, except less of semicolon for class definition. we can even take another class as our parameter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>

class two {
	std::string name;

public:
	two (std::string n):
		name (n)
		{
		}
	std::string print () {
		return name;
	}
};

class one {
	two c_two;
	int num;

public:
	one (two c, int p):
		c_two (c),
		num (p)
		{
		}
	void print () {
		std::cout << "c_two: " << c_two.print() << std::endl;
		std::cout << "num: " << num << std::endl;
	}
};

int main() {
	two two_object ("chipp");
	one one_object (two_object, 19);
	one_object.print();
	std::cin.get();
	return 0;
}


CMIIW
Topic archived. No new replies allowed.