473,602 Members | 2,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling Inherited Constructors

Hello, first time posting.
If I have a base class and a derived class, is there only one way to
call the base constructor?

i.e. Is this the only way I can call the base constructor (presuming
the base constructor took an int):

Derived::Derive d(int a) : Base(a)
{ ... }

I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?

Thanks for any help,
Justin

Nov 3 '05 #1
6 2101
> I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?


no, there is no way to do what you in intend with constructors.

a solution would be to move initialization in the base class to a
protected method, which you can then call in the derived class ctor
after you ran your code there.

this doesn't work though if the code in the derived class is to be
executed before any parent class instance members are initialized, as
this already happens in the parent ctor. then you would have to delay
initializing these too by not storing by value...

Nov 3 '05 #2
Justin wrote:

Hello, first time posting.

If I have a base class and a derived class, is there only one way to
call the base constructor?

i.e. Is this the only way I can call the base constructor (presuming
the base constructor took an int):

Derived::Derive d(int a) : Base(a)
{ ... }
I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?


well. not exactly.
But a there is a small gap in the door :-)

Derived::Derive d(int a) : Base( foo( a ) )
{
}

int Derived::foo( int arg )
{
// now you can do whatever you want
// before the base ctor gets called

// but beware
// the Derived class object has not been fully constructed yet,
// so be careful in what you do

return arg;
}
--
Karl Heinz Buchegger
kb******@gascad .at
Nov 3 '05 #3
Ed
You should make the foo member function static thus avoiding any
possibility of doing anything that is undefined.

Ed
Karl Heinz Buchegger wrote:
Justin wrote:

Hello, first time posting.

If I have a base class and a derived class, is there only one way to
call the base constructor?

i.e. Is this the only way I can call the base constructor (presuming
the base constructor took an int):

Derived::Derive d(int a) : Base(a)
{ ... }

I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?


well. not exactly.
But a there is a small gap in the door :-)

Derived::Derive d(int a) : Base( foo( a ) )
{
}

int Derived::foo( int arg )
{
// now you can do whatever you want
// before the base ctor gets called

// but beware
// the Derived class object has not been fully constructed yet,
// so be careful in what you do

return arg;
}
--
Karl Heinz Buchegger
kb******@gascad .at


Nov 3 '05 #4
Aha! Thank you Karl, that is exactly what I needed. Don't worry, I
wasn't intending to do anything with the partially constructed base
class at all. The base class was originally designed to be declared
and used exclusively as private member data for a class that used it as
an internal data type, but since I have pulled it out to use it
independently. The issue arose when I pulled it from the outer class
that contained code in its constructor to parse an XML file and open
some files..etc.

Thanks again

Nov 3 '05 #5
Aha! Thank you Karl, that is exactly what I needed. Don't worry, I
wasn't intending to do anything with the partially constructed base
class at all. The base class was originally designed to be declared
and used exclusively as private member data for a class that used it as
an internal data type, but since I have pulled it out to use it
independently. The issue arose when I pulled it from the outer class
that contained code in its constructor to parse an XML file and open
some files..etc.

Thanks again

Nov 3 '05 #6
Justin wrote:
Hello, first time posting.

If I have a base class and a derived class, is there only one way to
call the base constructor?
No. Constructors can be overloaded. The base can have many possible
constructors for you to call. If you don't specify one, then the
default one is used.

If there isn't a default one, and your constructor doesn't call it from
its initializer list, then you have an error.
i.e. Is this the only way I can call the base constructor (presuming
the base constructor took an int):

Derived::Derive d(int a) : Base(a)
{ ... }
This is the only way you can call /that/ base class constructor, yes.
I know the base class must be constructed before the derived class
is..so I guess my question is, is there any way that I can run some
code in the derived constructor before calling the base constructor?


No. You can only call base constructors in the base and member
initializer list.

Moreover, the order of appearance of expressions in that list isn't
necessarily the order in which they are evaluated. Be careful! The list
is a specification of what component gets what initialization. It is
not a sequential program.

If you call a constructor in an ordinary statement body, what happens
is that it returns a temporary object. A constructor is not invoked on
the ``this'' object.

By the time you run the constructor body, the base class parts are
already constructed. You can adjust the base class object by assigning
to its members, or calling additional routines in the base class
(two-step initialization) .

There is also a way to call a constuctor on some given piece of memory.
This is done by the so called ``placement new'' operator.

There is a trick you can do to re-initialize a base class differently.
You do a in-place destructor call to wipe out the base, and then a
placement new over it.

I would put this in the category of "black art", and would never do it
over anything other than bases which are POD's (plain old datatypes).
I'm pretty sure the behavior is undefined, since basically we are
destroying an object midway through a construction, re-constructing
that destroyed part of it and then depending on the remainder of the
construction going fine to build the derived parts on top of the
reconstructed bases.

:)

Nov 4 '05 #7

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

Similar topics

3
1763
by: SLE | last post by:
Hi there, I know constructors are not inherited from the base class, not in VB.NET nor C# (nor Java I suppose). I never wondered,but reflecting on the reason why, I cannot find a solid answer. Is the reason technical (compiler or CLR limitation) or logical (OOP best practices)? Any feedback would be greatly appreciated.
3
1426
by: Alexander Muylaert | last post by:
Hi Is their a way to keep constructors visible in inherited classes? public class X{ public x(int A){} } public class Y : X{};
4
1622
by: Claire | last post by:
I'm having real brain failure today. I've done this lots of times with constructors but not with virtual methods and the compiler complains because Ive put the :base(foo) after the function header. I want to call the BaseResult class to let it write shared data before I let the derived class write its own data. What am I doing wrong please. public abstract class BaseResult {
2
1481
by: PIEBALD | last post by:
OK, here's my latest workaround for the lack of inherited constructors... It requires that the class have a parameterless (default) constructor and a public virtual "Initialize" method (which returns its "this"). An instance (in this case a Number) is constructed and initialized like so: Number n = ((Number)((Number) typeof(Number).GetConstructor(System.Type.EmptyTypes).Invoke(new object{})).Initialize(1)) ;
3
1243
by: M O J O | last post by:
Hi, I've created a MasterForm which all my forms in my project must derive from. In my MasterForm, I've overloaded the New event with this code: Public Sub New(ByVal SomeText As String) MyBase.New()
20
3214
by: lars.uffmann | last post by:
I have to work on a rather big project that a bunch of people wrote and that has no useful documentation at all, my C++ has rusted in a bit, now I stumbled over a constructor that looks something like the below and have no idea what to do with it :) inheritedClass::inheritedClass () : originalConstructor () , m_cells(cells), m_srfcs(srfcs) {
3
5468
by: Wayne Brantley | last post by:
VS2005 RTM Create a web user control to use as a base class for other web user controls. Now, create a new web user control, change the class it inherits from to your base class and compile. (You must have a <% Register %> so it will see it) You will get TWO warnings per class like:
12
1766
by: Oleg Subachev | last post by:
I am moving from Delphi to C# and hve encountered the problem: I have the following classes and form Load event handler: public class class1 { public string S; public class1( string aS ) { S = aS;
2
1559
by: Søren M. Olesen | last post by:
Hi How do I create an instance of an object with an inherited cunstructor?? In the below example, I'm able to create an instance of MyClass2 using the forst two lines of code, however if I try using the next two lines of code it fails.
0
7993
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7920
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
8401
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
8404
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
8268
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
3900
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...
1
2418
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
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
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.