I have problem with making class that has another class as attribute

Hi! I have problem with making class that has another class as an attribute. I want to make class elem that has as attribute class col that looks like this:
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
class col{
private:
    int x;
    int y;
    int z;
public:
    col( ){
        x=255;
        y=255;
        z=255;
    }
    col(int a, int b, int c){
        if (a>=0 && a<=255 && b>=0 && b<=255 && c>=0 && c<=255){
            x=a;
            y=b;
            z=c;
        }
        else
            throw 1;
    }
    int getX(){
        return x;}
    int getY(){
        return y;}
    int getZ(){
        return z;}

};

now class elem must have a private attribute (color) type col. Class elem needs to have constructor with one parameter type col. If we do not pass anything as parameter, constructor attribute color sets to 255,255,255 value. Also I need an option to change current value of color as well as one setter and one getter.
Last edited on
Hello & Welcome,

Please put your code between code tags, like these:


[code]

[/code]



Next, where do we see class elem?

Have a start on it?
First of all, thanks for the tip and welcome. I have started and so far I have wrote this, but I think that this is not correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Elem{

private:
col color;
public:
Elem(){
color(255,255,255);
}
Elem(R){
col(a,b,c);}




}
In the default constructor you have a few options, but you probably know that's not it.

One typical case would be:

Elem() : color( 255, 255, 255 ) {}

The same may apply to the next constructor, but I don't know what R is or means, and of course we would need some source for a, b & c, so think about that one and come back.
First, there is difference between initialization and assignment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
col::col()
 : x{255}, y{255}, z{255} // this is initialization
{
}

col::col( int a, int b, int c )
 : x{a}, y{b}, z{c} // wright or wrong, we initialize them
{
  if ( a>=0 && a<=255 && b>=0 && b<=255 && c>=0 && c<=255 ) {
    // parameters were ok, members are ok
  }
  else {
    throw 1;
  }
}

We do notice that the col does initialize to (255,255,255) by default.
Let Elem trust on that:
1
2
3
4
5
6
class Elem {
private:
  col color;
public:
  Elem() = default; // default constructor does the Right Thing
};


What is the R?
You said that the Elem "needs to have constructor with one parameter type col".
Wouldn't that be Elem( col a )?

Have you seen:
1
2
3
4
5
6
int x = 42;
int y {x}; // copy initialization

// or
std::string x( "Hello" );
std::string y( x ); // copy initialization 

Therefore,
1
2
3
4
Elem( col a )
 : color( a ) // initialize member
{
}
Thanks a lot. That works fine
Topic archived. No new replies allowed.