473,794 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling one constructor from another in VC++

I'm fairly new to C++ and VC++, but for the most part it seems to do most of
the same things that can be done in Java, with just some syntactic and
structural adjustments. However, one thing I haven't been able to figure out
is how to call one constructor from another within a class. It's easy enough
to call the base class's constructor from the derived class, but that's not
what I'm trying to do.

For example, in Java (or J#) it's easy to do this:

public class Circle
{
private int PointX;
private int PointY;
private int Radius;

public Circle()
{
this.PointX = 0;
this.PointY = 0;
this.Radius = 0;
}

public Circle(int x, int y)
{
this();
this.PointX = x;
this.PointY = y;
}

public Circle(int x, int y, int r)
{
this(x, y);
this.Radius = r;
}
}

However, trying to do the same thing in VC++ doesn't work:

// Sphere.h (partial file)
class Sphere
{
public:
Sphere(void);
Sphere(int x, int y);
Sphere(int x, int y, int r);
~Sphere(void);

private:
int PointX;
int PointY;
int Radius;
};

// Circle.cpp (partial file)
#include ".\circle.h "

Circle::Circle( void)
{
this->PointX = 0;
this->PointY = 0;
this->Radius = 0;
}

Circle::Circle( int x, int y)
{
Circle();
this->PointX = x;
this->PointY = y;
}

Circle::Circle( int x, int y, int r)
{
Circle(x, y);
this->Radius = r;
}

In the C++ version, I also tried using this() instead of Circle(), which
caused a compiler error. I also tried doing it without the this-> specifier,
which made no difference. The end result if you call the second constructor
is that the X and Y values have been set, and the Radius is uninitialized.
If you use the third constructor, you get exactly the opposite results. (And
I don't mean they have values of zero; looking at them with the debugger, I
see values of -842150451 for the uninitialized members.)

So is there any way in C++ to let one constructor build on another like
this?

Thanks for any help.
Nov 17 '05
31 5196
Hendrik Schober wrote:
Arnold the Aardvark <no@way.com> wrote:
[...]
He's lost me a bit there. :-( 'standard argument lists'?


Me too. :)


I think what he's talking about is the situation where you have a class that
has several constructors, all of which have a common subset of parameters
(the 'standard argument list'), with each constructor adding one or more
additional arguments beyond that. Default parameters can allow you to
collapse that into fewer constructors.

-cd
Nov 17 '05 #21
Carl Daniel [VC++ MVP] <cp************ *************** **@mvps.org.nos pam> wrote:
[...] the object is considered constructed at the start of the
constructor body. Afterall, an exception thrown from within the constructor
body will invoke the destructor.
Is this true? I didn't think so.
[...]
-cd

Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #22
Hendrik Schober wrote:
Carl Daniel [VC++ MVP]
<cp************ *************** **@mvps.org.nos pam> wrote:
[...] the object is considered constructed at the start of the
constructor body. Afterall, an exception thrown from within the
constructor body will invoke the destructor.


Is this true? I didn't think so.


You're right - it's not. Destructors for fully constructed sub-objects will
be invoked.

Nonetheless, I believe that the awful thing I showed up above is technically
legal. Legal or not, it's done it real-world code that I've come across.

-cd
Nov 17 '05 #23
Carl Daniel [VC++ MVP] wrote:
Hendrik Schober wrote:
Arnold the Aardvark <no@way.com> wrote:
[...]
He's lost me a bit there. :-( 'standard argument lists'?


Me too. :)


I think what he's talking about is the situation where you have a class
that has several constructors, all of which have a common subset of
parameters (the 'standard argument list'), with each constructor adding
one or more
additional arguments beyond that. Default parameters can allow you to
collapse that into fewer constructors.


Yes that makes sense, though it sort of contradicts the idea that
default arguments were pre-overloading: He says they were introduced
to curb overloading, but that overloading makes default arguments
redundant. Maybe he meant something else. Um... who cares anyway?
Arnold the Aardvark

'Failure of intelligence' or 'failure of democracy'? They
lied and thousands died, but corporations made money, and
that's all that matters, isn't it?
Nov 17 '05 #24
[I see there have been some other replies to this message in the interim;
probably by now somebody else has hit on the same solution.]

With the help of an ingenious friend (thank you, Theo!), I was able to find
out how to make the constructor calls that I wanted. It's kind of an
odd-looking construct, and since no one here knew about it, I guess it's not
something that's commonly done in C++.

On the off-chance that it'll be useful to someone else, here's the code:

// From file Sphere.h

class Sphere
{
public:
Sphere(void);
Sphere(int x, int y, int z);
Sphere(int x, int y, int z, int r);
~Sphere(void);
System::String *ToString();

private:
int CenterX;
int CenterY;
int CenterZ;
int Radius;
};

// From file Sphere.cpp

Sphere::Sphere( void)
{
this->CenterX = 0;
this->CenterY = 0;
this->CenterZ = 0;
this->Radius = 0;
}

Sphere::Sphere( int x, int y, int z)
{
//Sphere(); // Wrong! Just makes and destroys temp object
this->Sphere::Sphere (); // Right! Initializes all members.
this->CenterX = x;
this->CenterY = y;
this->CenterZ = z;
}

Sphere::Sphere( int x, int y, int z, int r)
{
//Sphere(x, y, z); // Wrong! Just makes and destroys temp object
this->Sphere::Sphere (x, y, z); // Right! Initializes all members.
this->Radius = r;
}

Sphere::~Sphere (void)
{
}

String *Sphere::ToStri ng()
{
String *sReturn = S"";

sReturn = String::Format( S"Sphere is centered at [X={0}, Y={1}, Z={2}]",
CenterX.ToStrin g(), CenterY.ToStrin g(), CenterZ.ToStrin g());
sReturn = String::Concat( sReturn,
String::Format( S"\nSphere has a radius of {0}", Radius.ToString ()));

return sReturn;
}

// From file ConstructorTest .cpp

int _tmain()
{
Sphere *sphere1 = new Sphere();
Sphere *sphere2 = new Sphere(10, 100, 1000);
Sphere *sphere3 = new Sphere(5, 50, 500, 5000);

Console::WriteL ine(S"Sphere1: {0}", sphere1->ToString());
Console::WriteL ine(S"Sphere2: {0}", sphere2->ToString());
Console::WriteL ine(S"Sphere3: {0}", sphere3->ToString());
return 0;
}

With the incorrect constructor calls (commented out in the code above), the
result of executing ConstructorTest .exe is:

Sphere1: Sphere is centered at [X=0, Y=0, Z=0]
Sphere has a radius of 0
Sphere2: Sphere is centered at [X=10, Y=100, Z=1000]
Sphere has a radius of -842150451
Sphere3: Sphere is centered at [X=-842150451, Y=-842150451, Z=-842150451]
Sphere has a radius of 5000

But with the correct ones, the result is:

Sphere1: Sphere is centered at [X=0, Y=0, Z=0]
Sphere has a radius of 0
Sphere2: Sphere is centered at [X=10, Y=100, Z=1000]
Sphere has a radius of 0
Sphere3: Sphere is centered at [X=5, Y=50, Z=500]
Sphere has a radius of 5000
Nov 17 '05 #25

"Arnold the Aardvark" <no@way.com> wrote in message
news:bv******** **********@news .demon.co.uk...
What you are attempting is a Java idiom not a C++ one. Don't be mislead by
superficial similarities in syntax; they are totally different animals.
Just exploring the capabilities of the language. It's a construct that I've
gotten used to, and since I didn't see any mention of it in C++ docs, I
wanted to know if it was available. This was more a curiosity than a crisis.
You should definitely prefer member initialiser lists:

Circle::Circle( )
: PointX(0), PointY(0), Radius(0)
{ }

Circle::Circle( int x, int y)
: PointX(x), PointY(y), Radius(0)
{ }

Circle::Circle( int x, int y, int r)
: PointX(x), PointY(y), Radius(r)
{ }
Those look like they could be useful; not something I'd run across in my
reading yet.
FWIW I learnt Java and C++ the other way around. I find I miss little
things, too: templates, RAII, type safe containers... Ho hum.


C++ has been absent from my repertoire of languages for far too long; since
it still seems to be the dominant language for development, I figured it's
about time to correct that.

Thanks for all your help.

- Peter
Nov 17 '05 #26
Peter E. Granger wrote:
[I see there have been some other replies to this message in the interim;
probably by now somebody else has hit on the same solution.]

With the help of an ingenious friend (thank you, Theo!), I was able to find
out how to make the constructor calls that I wanted. It's kind of an
odd-looking construct, and since no one here knew about it, I guess it's not
something that's commonly done in C++.

On the off-chance that it'll be useful to someone else, here's the code:

Sphere::Sphere (int x, int y, int z, int r)
{
//Sphere(x, y, z); // Wrong! Just makes and destroys temp object
this->Sphere::Sphere (x, y, z); // Right! Initializes all members.
this->Radius = r;
}


The above is bogus, both from a Standard C++ point of view and conceptually,
because even if it were legal, it would be equivalent to using placement new
on a partially constructed object and would be wrong for all the reasons
that method is wrong. It's a non-standard leftover from the dark ages of
VC++. Don't use it. You've been given correct answers by myself and others
in this thread.

--
Doug Harrison
Microsoft MVP - Visual C++
Nov 17 '05 #27
Yes, do not use this. It is not guaranteed to continue working. And most
likely will indeed stop working in some future version.

If it is any consolation "delegating constructors" are on the C++ Standards
committee list of the possible feature additions.

Ronald Laeremans
Visual C++ team

"Doug Harrison [MVP]" <ds*@mvps.org > wrote in message
news:l0******** *************** *********@4ax.c om...
Peter E. Granger wrote:
[I see there have been some other replies to this message in the interim;
probably by now somebody else has hit on the same solution.]

With the help of an ingenious friend (thank you, Theo!), I was able to findout how to make the constructor calls that I wanted. It's kind of an
odd-looking construct, and since no one here knew about it, I guess it's notsomething that's commonly done in C++.

On the off-chance that it'll be useful to someone else, here's the code:

Sphere::Sphere (int x, int y, int z, int r)
{
//Sphere(x, y, z); // Wrong! Just makes and destroys temp object
this->Sphere::Sphere (x, y, z); // Right! Initializes all members.
this->Radius = r;
}
The above is bogus, both from a Standard C++ point of view and

conceptually, because even if it were legal, it would be equivalent to using placement new on a partially constructed object and would be wrong for all the reasons
that method is wrong. It's a non-standard leftover from the dark ages of
VC++. Don't use it. You've been given correct answers by myself and others
in this thread.

--
Doug Harrison
Microsoft MVP - Visual C++

Nov 17 '05 #28
Peter E. Granger <PE******@hotma il.com> wrote:
"Arnold the Aardvark" <no@way.com> wrote in message
news:bv******** **********@news .demon.co.uk...
What you are attempting is a Java idiom not a C++ one. Don't be mislead by
superficial similarities in syntax; they are totally different animals.
Just exploring the capabilities of the language. It's a construct that I've
gotten used to, and since I didn't see any mention of it in C++ docs, I
wanted to know if it was available. This was more a curiosity than a crisis.


FWIW, when I started to learn C++,
I tried that, too. Unfortunately,
the compiler I used back then did
support it, forcing me to change
the code later.
You should definitely prefer member initialiser lists:

[...]

Those look like they could be useful; not something I'd run across in my
reading yet.


Uh. What are you reading???
[...]
C++ has been absent from my repertoire of languages for far too long; since
it still seems to be the dominant language for development, I figured it's
about time to correct that.
Good idea. :)
Thanks for all your help.

- Peter

Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #29
Peter E. Granger <PE******@hotma il.com> wrote:
[I see there have been some other replies to this message in the interim;
probably by now somebody else has hit on the same solution.]
Yes. And hopefully they have abandoned it by now.
With the help of an ingenious friend (thank you, Theo!), I was able to find
out how to make the constructor calls that I wanted. It's kind of an
odd-looking construct, and since no one here knew about it, I guess it's not
something that's commonly done in C++.
1. No, people do know about it.
2. Yes, it isn't done commonly -- and that's
for good reasons.
On the off-chance that it'll be useful to someone else, here's the code:
[snipped code that attempts to call a ctor

on an already constructed object]
Once again, this is the simplest solution
to your problem:

Sphere(int x=0, int y=0, int z=0, int r=0)
: CenterX(x), CenterY(y), CenterZ(z), Radius(r)
{
}

What is tehre to miss?

Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1870
by: Alexander Stippler | last post by:
Hi I have already posted and discussed the following problems once, but despite really helpful hints I did not get any further with my problem (I at least learned, first to exactly consider why something does not work instead of immediately searching for work arounds) . I have the following code resulting in an ambiguity: -------------------------------------------------------- template <typename Impl> class Vector {};
1
7099
by: david | last post by:
I have a question (not sure if just a newbie one, or a stupid one) whose answer I couldn't find on the C# books and tutorials I could put my hands on. Consider the following useless class (could be a struct as well, if you just comment out the non static parameterless constructor) and the Main() routine : using System;
2
2197
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to instantiate an array of structures; consider the following useless code : using System; struct MyPointS
7
6788
by: Bonj | last post by:
OK I know a constructor can't have a return value but is it feasible such that I have a class whereby //in MyClass1. class MyClass MyClass1(){} ~MyClass1(){} MyClass1(int & Result) {Result = InitMyClass()} int InitMyClass()
17
2204
by: Bill Grigg | last post by:
I have been successfully calling DLL's using VC++ 6.0 and also using VC++7.1 (.NET). I only mention this because I have never felt comfortable with the process, but nonetheless it did work. Recently I started calling an unmanaged DLL from a .NET app. It worked fine. Now I have the situation where I am trying to call a function in one DLL from another DLL. Both are unmanaged and are built with VC++7.1. In the calling DLL I set the property...
12
2711
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
6
2467
by: daveb | last post by:
I'm trying to write some code that calls the constructors of STL containers explicitly, and I can't get it to compile. A sample program is below. One compiler complains about the last two lines (the map constructor calls), saying that I'm trying to take the address of a constructor. Another compiler complains about all four of the last lines, just saying "invalid use of class". What is the correct syntax for calling a container...
7
2689
by: =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post by:
I have a C# logging assembly with a static constructor and methods that is called from another C# Assembly that is used as a COM interface for a VB6 Application. Ideally I need to build a file name based on the name of the VB6 application. A second choice would be a file name based on the # COM interface assembly. I have tried calling Assembly.GetCallingAssembly() but this fails when I use the VB6 client. Is there a way to get this...
3
1415
by: =?Utf-8?B?TmFkYXY=?= | last post by:
Hi, I am trying to manually call a constructor of a template argument, the compiler returns “error C2039: ‘T’ : is not a member...” How can I manually call the constructor of a template argument? Please note that I cannot use the ‘new’ operator ( as long as it allocates memory ), see the following code snnipet as an example of what I am trying to do.
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6777
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.