473,794 Members | 2,804 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 5198
Hmmmm. Why do you say that explicit qualification is bogus/illegal from a
Standard C++ point of view? I can buy that using it to call another
constructor on a partially constructed object might be a mistake, but I
question the "even it it were legal" and "its non-standard" assertions.
Explicit qualification appears to be perfectly legal and standard C++. Is
it not? From Section 10.2 "Member name lookup" of the C++ standard

12 Explicit qualification with the scope operator (5.1) suppresses the
virtual call mechanism. [Example:

class B { public: virtual void f(); };

class D : public B { public: void f(); };

void D::f() { /* ... */ B::f(); }

Here, the function call in D::f really does call B::f and not D::f. ]
And there are other places in the standard where explicit qualification is
used to make various points. I easily believe that using explicit
qualification to call one constructor from another is bad, but I would like
to better understand why. My own guess is that it would be bad because it
could cause double invocation of constructors for all nodes of the
inheritance graph and their data members. If that were not anticipated
throughout the entire graph it could result in leaks and hard to find bugs.
Is that why?

The constructor scenario aside, suppose that I want to augment a regular
non-pure virtual method that I am overriding rather than replace it
wholesale. Isn't it perfectly fine to use explicit qualification to supress
the virtual call mechanism in order to invoke base class method
implementation and then add my other additional logic?

-Bern McCarty

"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 #31
Bern McCarty wrote:
Hmmmm. Why do you say that explicit qualification is bogus/illegal from a
Standard C++ point of view?
I didn't say that.
I can buy that using it to call another
constructor on a partially constructed object might be a mistake, but I
question the "even it it were legal" and "its non-standard" assertions.
Explicit qualification appears to be perfectly legal and standard C++.
You can't directly call a constructor. Thus the following is illegal:
Sphere::Sphe re(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;
}

Is it not? From Section 10.2 "Member name lookup" of the C++ standard
See 12.1/2.
And there are other places in the standard where explicit qualification is
used to make various points. I easily believe that using explicit
qualificatio n to call one constructor from another is bad, but I would like
to better understand why. My own guess is that it would be bad because it
could cause double invocation of constructors for all nodes of the
inheritance graph and their data members. If that were not anticipated
throughout the entire graph it could result in leaks and hard to find bugs.
Is that why?
That's certainly one very big reason. This being C++, there may be some more
obscure ones I haven't thought of. :)
The constructor scenario aside, suppose that I want to augment a regular
non-pure virtual method that I am overriding rather than replace it
wholesale. Isn't it perfectly fine to use explicit qualification to supress
the virtual call mechanism in order to invoke base class method
implementati on and then add my other additional logic?


Yep.

--
Doug Harrison
Microsoft MVP - Visual C++
Nov 17 '05 #32

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

Similar topics

11
1871
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
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10213
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10163
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
9037
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6779
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
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.