473,786 Members | 2,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constructor Initialization

Hi,

It seems I can influence how a base class is initialized beyond the
'normal' manner and I was wondering if someone can tell me why this.
Here's my example.

class A
{
public:
A(int a=1, int b=1, int c=1) : _a(a), _b(b), _c(c) {}
void print()
{ cout << _a << "," << _b << "," << _c << endl; }
private:
int _a, _b, _c;
};

class B : public virtual A
{
public:
B(int a=1, int b=1, int c=1) : A(a, b, c) {}
};

class C : public virtual B
{
public:
C(int a=1, int b=1, int c=1)
:
B(a, b, c),
A(2,2,2) // I can explicitly initialize A here and override
the default values
{}
};

main()
{
C c;
c.print();
}
thanks,
Mike

Jul 19 '05 #1
5 9464

"Michael McKnerney" <mi************ ***@baesystems. com> wrote in message news:3E******** *******@baesyst ems.com...
Hi,

It seems I can influence how a base class is initialized beyond the
'normal' manner and I was wondering if someone can tell me why this.
Because you have virtual base classes. The most derived class must initialize
all the virtual bases. The initialization of A specified in the B constructor has no
bearing on the creation of C objects.
main()
{


You must provide an int return here (even in C these days).
Jul 19 '05 #2
On Fri, 27 Jun 2003 17:39:03 +0000, Michael McKnerney wrote:
Hi,

It seems I can influence how a base class is initialized beyond the
'normal' manner and I was wondering if someone can tell me why this.
Here's my example.

[snip]......
For virtual bases, the rule is different. The most derived class is
responsible for constructing the virtual base class, as opposed to its
immediate descendant in case of non-virtual bases.

HTH,
-Dhruv.


Jul 19 '05 #3


Dhruv wrote:
On Fri, 27 Jun 2003 17:39:03 +0000, Michael McKnerney wrote:
Hi,

It seems I can influence how a base class is initialized beyond the
'normal' manner and I was wondering if someone can tell me why this.
Here's my example. [snip]......

For virtual bases, the rule is different. The most derived class is
responsible for constructing the virtual base class, as opposed to its
immediate descendant in case of non-virtual bases.


But wait a minute, if I remove the explicit initialization of A in C's
constructor list, A will get initialized by B.


HTH,
-Dhruv.


Jul 19 '05 #4

"Michael McKnerney" <mi************ ***@baesystems. com> wrote in message news:3E******** ******@baesyste ms.com...
But wait a minute, if I remove the explicit initialization of A in C's
constructor list, A will get initialized by B.


No it will not. If you remove the explicit initialization, it will invoke the
default constructor. If A didn't have a default constructor, then you'd
get an error.
Jul 19 '05 #5
Michael McKnerney wrote:

Dhruv wrote:

On Fri, 27 Jun 2003 17:39:03 +0000, Michael McKnerney wrote:

Hi,

It seems I can influence how a base class is initialized beyond the
'normal' manner and I was wondering if someone can tell me why this.
Here's my example.


[snip]......

For virtual bases, the rule is different. The most derived class is
responsible for constructing the virtual base class, as opposed to its
immediate descendant in case of non-virtual bases.


But wait a minute, if I remove the explicit initialization of A in C's
constructor list, A will get initialized by B.


Nope. If you remove the explicit initialization of A in C's initializer
list and then invoke the class C ctor,

C(int a=1, int b=1, int c=1)
: B(a,b,c)
{ }

the sequence of events (IIRC) is this:

1) Program invokes the C ctor
2) The C ctor implicitly invokes A's default ctor
3) The C ctor invokes 'B(a,b,c)' as specified in the initializer list of
the class C ctor. The B ctor does not invoke the A ctor.

So the class C ctor -- not the B ctor -- is still the entity that
invokes the class A ctor.
FWIW, if you rewrite your code a bit, this sequence of events will (IMO)
be easier to observe.

<example>
<code>

#include <iostream>
using namespace std;

class A {
public:
A(int a=1, int b=1, int c=1)
: a_(a), b_(b), c_(c)
{ cout << "A(" << a << ',' << b << ',' << c << ")\n"; }

void print()
{ cout << a_ << ',' << b_ << ',' << c_ << '\n'; }

private:
int a_, b_, c_;
};

class B : public virtual A {
public:
B(int a=2, int b=2, int c=2)
: A(a, b, c)
{ cout << "B(" << a << ',' << b << ',' << c << ")\n"; }
};

class C : public virtual B {
public:
C(int a=3, int b=3, int c=3)
// : A(4,4,4), B(a,b,c)
: B(a,b,c)
{ }
};

int main()
{
C c;
c.print();
}

</code>

<output>
A(1,1,1)
B(3,3,3)
1,1,1
</output>

</example>
Some side notes:

1) DO NOT use variable names that start with a leading underscore, e.g.,
'_a'. These names (and some others) are reserved for the
implementation' s use -- e.g., the standard library, compiler-specific
language extensions, the OS's API, etc. So if you want to use
underscores to denote variable names, place the underscore at the end of
the name, 'a_', and not at the beginning.

2) In this code sample, class A's ctor is *always* invoked before class
B's ctor. This sequence holds even if you try (futilely) to specify the
base class ctor invocation sequence as B first, then A, in the class C
ctor initializer list:

C() : B(), A() { }

IOW, the compiler ignores the B,A sequence specified above, and
implicitly implements C's initializer list as A,B, i.e.,

C() : A(), B() { }

[n.b. Most compilers are nice enough to warn you when they implicitly
reorder the initializer list's arguments like this.]

--
Jim

To reply by email, remove "link" and change "now.here" to "yahoo"
jfischer_link58 09{at}now.here. com
Jul 19 '05 #6

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

Similar topics

2
4715
by: Grumble | last post by:
Hello all, What, if any, is the difference between string s("toto"); string s = "toto"; In the first case, I am using the constructor: basic_string(const value_type *ptr);
11
580
by: Kurt Krueckeberg | last post by:
Given a class X class X { public: X(int); X(const X&); //. . . }; Is this line X x1(1); the same thing as X x2 = 2;
6
2494
by: rona | last post by:
Hi everyone, Could someone tell us why the below code compiles and works? Is it legal in the constructor of class B? Cheers Ronny ---------------------------------
12
5819
by: NewToCPP | last post by:
does the default constructor initialize values? I have a class as defined below: class A { int i; char c; int * iPtr;
9
1985
by: toton | last post by:
Hi, Which one is the correct syntax for constructor for static memory allocation Object obj("param"); or Object obj = Object("param"); 1) For the first one, how compiler checks it as not a function deceleration rather than ctor call?
10
2033
by: imutate | last post by:
Some questions about ctors and class members Is v private in the following ? If it is why put the declaration at the top ? Is there any difference to putting it in the private section ? The reference to v() defines the constructor, it will call v's constructor, right ? class vec {
74
16036
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
14
1915
by: raylopez99 | last post by:
Question: the "myList" below is the same (works the same) whether instantiated inside the (normal) constructor, as below, and as my standard practice, or outside? RL public class AClass { int j;
4
351
by: t | last post by:
Suppose class A has no programmer-written constructors and the compiler generates a default constructor for it. Suppose class B is exactly like class A except it has a programmer-written default constructor with no initializer list and an empty body. Do the default constructors of A and B act the same in all situations?
3
2445
by: mhvaughn | last post by:
struct S1 { int i; }; struct S2 { S1 s; // version 1 S2() {} ; // version 2
0
9496
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,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10164
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...
0
9961
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
6745
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
5397
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4066
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
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.