Why is object initialized this way?

Chap on classes.
Why are objects initialized this way?
"Height myHeight(Height(6,3));"
This works just as well.
"Height myHeight(6,3);"


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 representing a height
value class Height
{
private:
// Records the height in feet and inches
int feet;
int inches;
public:
// Create a height from inches value
Height(int ins)
{
    feet = ins/12;
    inches = ins%12;
}
// Create a height from feet and inches
Height(int ft, int ins) : feet(ft), inches(ins){}
};

int main(array<System::String ^> ^args)
{
   Height myHeight(Height(6,3));
   Height^ yourHeight(Height(70));
    Height hisHeight(*yourHeight);
   Console::WriteLine(L”My height is {0}”, myHeight);
   Console::WriteLine(L”Your height is {0}”, yourHeight);
   Console::WriteLine(L”His height is {0}”, hisHeight);
   return 0;
}
Last edited on
> Why are objects initialized this way?
> "Height myHeight(Height(6,3));"

Probably written by a Java/C# programmer who has been conditioned to write:
Height myHeight = new Height(6,3) ;
and translated it verbatim by dropping the new

> This works just as well.
> "Height myHeight(6,3);"

That is what a real C++ programmer would write:
Height myHeight(6,3);
Thanks. That makes sense, since both work.
can i ask a question here:
the value of a constructor is an object of the class, that's what i know.
in this class, there's no constructor that takes an object argument.
why didn't this line cause an error:
Height myHeight(Height(6,3));
i thought there should be a
"no overloaded form of Height::Height() function meets this argument list : Height::Height(Height);"

error??
why did the compiler run this program normally ?

i'd appreciate the guidance, i'm a beginner though.
Copy constructor Foo::Foo(const Foo&) is declared imlicitly by compiler, as do default constructor and destructor.
So in your example there is 2 constructor calls: First temporary object constructed using parametrized constructor, then normal object created using copy constructor. Compiler will probably optimise this, but it is better to not rely on that.
Last edited on
thx dude, you rock.
Topic archived. No new replies allowed.