...

View Full Version : Can anyone shed some light please...



DaZ
02-06-2003, 11:41 AM
just starting out basically in C++

ive got a class declared like the following;

-----------------------------------------------------------------
class rectangle
{
public:
rectangle();
~rectangle();
void SetLength(int length){itslength = length;}
int GetLength() const { return itslength;}

void SetWidth(int width){itswidth = width;}
int GetWidth() const {return itswidth;}

private:
int itslength;
int itswidth;
};
-----------------------------------------------------------------

the part of the code i dont understand is when declaring the constructor function underneath that section of code, the book i have states that it should be like the following
-----------------------------------------------------------------
// rectangle constructor declaration
rectangle::rectangle():
itswidth(5),
itslength(10)
{}
-----------------------------------------------------------------

now, this compiles and works correctly. and sets the member variables to 5 and 10 for itswidth and itslength.

however the only way ive learned to do this before is
// rectangle constructor declaration
rectangle::rectangle()
{
itswidth =5;
itslength=10;
}

this code also works correctly and compiles fine.

is the code ive put in above, that came with the book some kind of shortcut?? or does C++ allow for slight typos.

codefox
02-06-2003, 01:21 PM
rectangle::rectangle():
itswidth(5),
itslength(10)
{}
It's been sometime since I used C++. The above declaration works for user-defined data types. For Example,
I have two classes A and B with some contructors.

And, I have another class C which has two objects one each of the above mentioned classes. You may pass the parameters to the constructors of the objects of classes A and B as above.

class A {
public:
A() {
cout << "No-arg constructor";
}

A(int i) {
cout << i;
}
}

class B {
public:
B() {
cout << "No-arg constructor";
}

B(int i, float f) {
cout << i << f;
}
}

class C {
private:
A oa;
B ob;

public:
C() {
cout << "No-arg constructor";
}
C(float f, int i):oa(i), ob(i, f) {}
}

Calling the constructor of class C with two args would in turn call the one-arg constructor of oa and the two-arg constructor of ob.

codefox
02-06-2003, 01:22 PM
I dont know if it works for primitive data types too.

DaZ
02-17-2003, 09:52 AM
nice one thanks.

its just that the book ive got goes along quite happily, and then it throws something like that in and doesnt explain it..

thanks again for clearing it up for me.
DaZ



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum