473,763 Members | 8,483 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reusing super class constructor code

I have two classes:

aule_gl_window (parent class)

and

aule_button (sub class)

I want to call the super class (parent) constructor code from the sub
class constructor.

I am trying this:

aule_button::au le_button()
{
aule_gl_window: :aule_gl_window ();
}

and it does not work at all.

Any ideas?

Cheers!
Jul 19 '05 #1
7 13227
On Fri, 27 Jun 2003 20:44:44 -0700, Robin Forster wrote:
I have two classes:

aule_gl_window (parent class)

and

aule_button (sub class)

I want to call the super class (parent) constructor code from the sub
class constructor.

I am trying this:

aule_button::au le_button()
{
aule_gl_window: :aule_gl_window ();
}

and it does not work at all.

Any ideas?


When you instantiate the sub-class (derived class), the parent class' ctor
is called automatically before the derived class' ctor. You could call it
explicitly by writing it in the member initialization list, like:

aule_button::au le_button(): aule_gl_window( ) { }

HTH,
-Dhruv.


Jul 19 '05 #2
Robin Forster wrote:
I have two classes:

aule_gl_window (parent class)

and

aule_button (sub class)

I want to call the super class (parent) constructor code from the sub
class constructor.
There is no need to. The default constructors of every base class and
every member variable of class type are called automatically. If you
want a non-default constructor to be called instead, you can specify
that in the initializer list.

aule_button::au le_button()
: aule_gl_window( the, parameters)
{
}
I am trying this:

aule_button::au le_button()
{
aule_gl_window: :aule_gl_window ();
}

and it does not work at all.


Note that "does not work at all" is not a useful error description.

Jul 19 '05 #3
FYI, I was playing with inheritance yesterday to test how/whether the
child constructor/destructor would call those of the parent. Below is my
test code. Obviously I found out what people have been telling you: That
the child's constructor calls the parent's default constructor
automatically unless otherwise specified in the initializer list.

The attempt to call the parent's default constructor *outside* the
initializer list and actually in the body of the child's constructor bit
me, too (i.e., it did not initialize the child's data members). You said
that "did not work".

Suzanne
-------------------------------------------------------------------------------
// http://www.cs.unc.edu/~vogel/playpen...nheritance.cpp
/*************** *************** *************** *************** *************** ***
* File: Inheritance.cpp
* Purpose: Test inheritance, with use of parent's constructor and
destructor.
*************** *************** *************** *************** *************** ***/
#ifndef _STD_USING
#define _STD_USING // Must be #define'd in order to include stddef.h.
#endif // _STD_USING

#include <iostream>

class Parent {
public:
static const int filler = 99;
int* ints;
int n;
int magicNumber;
public:
Parent(const int n=10) {
std::cout << "Parent constructor #1\n";
this->n = n;
this->ints = new int[n];
for (int i=0; i<this->n; i++) {
this->ints[i] = Parent::filler;
}
this->magicNumber = -1;
}
Parent(const int n, const int m) {
std::cout << "Parent constructor #2\n";
this->n = n;
this->ints = new int[n];
for (int i=0; i<this->n; i++) {
this->ints[i] = Parent::filler;
}
this->magicNumber = m;
}
~Parent() {
std::cout << "Parent destructor\n";
delete[] this->ints;
}
};

class Child : public Parent {
public:
Child(const int n=10) {//: Parent(n) { // Parent default
constructor called automatically!
std::cout << "Child constructor #1\n";
}
Child(const int n, const int m) : Parent(n,m) { // Call parent
constructor!!!
std::cout << "Child constructor #2\n";
//Parent::Parent( n,m); // This is *not* valid!
}
~Child() { // Parent destructor is called automatically!
std::cout << "Child destructor\n";
}
};

int main(int argc, char** argv) {

// 1. Test whether parent destructor is called automatically (it is).
Child* c0 = new Child();
int* a = c0->ints;
delete c0;

if (a[0]==Parent::fille r) {
std::cout << "ERROR: Child not deleted!\n"; // Not printed out
(Good!)
}
std::cout << a[0] << "\n"; // Senseless number (Good!)

//-------------------------------------------------------------------------
// 2. Test whether parent constructor is called automatically (it is),
// and how. Turns out the *default* parent constructor is called
automatically,
// unless the child calls another constructor *before* the block {}.

std::cout <<
"//--------------------------------------------------------\n";
Child* c1 = new Child(99, 10);
int* b = c1->ints;

std::cout << "magic number: " << c1->magicNumber << "\n";
std::cout << b[0] << "\n";
delete c1;

return 1;
}

Jul 19 '05 #4
"Dhruv" <dh*******@gmx. net> wrote...
On Fri, 27 Jun 2003 20:44:44 -0700, Robin Forster wrote:
I have two classes:

aule_gl_window (parent class)

and

aule_button (sub class)

I want to call the super class (parent) constructor code from the sub
class constructor.

I am trying this:

aule_button::au le_button()
{
aule_gl_window: :aule_gl_window ();
}

and it does not work at all.

Any ideas?


When you instantiate the sub-class (derived class), the parent class' ctor
is called automatically before the derived class' ctor. You could call it
explicitly by writing it in the member initialization list, like:

aule_button::au le_button(): aule_gl_window( ) { }


This technique is called "initialisa tion of base classes", not
"calling constructors explicitly". Please do not confuse others.
Constructors cannot be called.

Victor
Jul 19 '05 #5
Thanks for the input. I am inferring that the following is a
possibility:

sub class:

aule_button::au le_button(int width, int height): aule_gl_window( TYPE,
width, height)
{
etc...
}

where TYPE is some constant that initializes a super class instance
variable.
Jul 19 '05 #6
Suzanne Vogel wrote:
Rolf,

Thanks for your tips. I didn't expect to get tips when I posted my
code.
When I answer postings that contain source code, I always give tips if I
can, even if they weren't asked for. I hope not to look too much like a
smartass by doing so. I just want to help clear things up.
Rolf Magnus wrote:
Suzanne Vogel wrote:
#ifndef _STD_USING
#define _STD_USING // Must be #define'd in order to include stddef.h.
#endif // _STD_USING


Er, what?


On my computer, if I don't write "#define _STD_USING" before trying to
include stddef.h (or some other header files), I get an error that the
"exit()" function is not defined.


Hmm. Sounds strange.
It's not really useful to declare a function or constructor as taking
a const parameter by value, since the function body cannot change the
argument that's passed to it anyway.


Oh.
You could (and should) put initializations in an initializer list.
Also note that this->... isn't needed.


I use "this->" before each data member only as a means of documenting
my code, to denote that I'm using data members and not local function
variables. Some people document data members by naming them with
something like "m_[something]", but I don't to modify the names of the
data members so I simply modify my syntax of how I access them
("this->"). Other suggestions welcomed...


I see. Would be too much typing for my taste :)
int main(int argc, char** argv) {

// 1. Test whether parent destructor is called automatically (it
is). Child* c0 = new Child();
int* a = c0->ints;
delete c0;

if (a[0]==Parent::fille r) {

That's not a good idea. If the parent part is deleted (which it is),
you are trying to access memory that doesn't belong to your program
anymore. Depending on your platform and the "situation" or maybe on
the moon phase, a[0] might still be set to Parent::filler, or it
might be overwritten with something else, or your program might get
terminated because you're not allowed to access that memory anymore,
or anything else can happen. DON'T do that!


I did it just as a test to see whether the parent destructor was
properly selected. I *knew* that if the data came back senseless (as
it did), then the parent destructor had been selected. (The opposite
would not necessarily be true, as you pointed out: It is *not*
necessarily true that if the data did not come back senseless, then
the parent destructor had not been selected.)


Ok. I just wanted to note that nobody should expect your test to show
what really happens. It might be the case on your OS/compiler
combination, but this can be different on other systems.

Jul 19 '05 #7
aule_button::au le_button(): aule_gl_window( ) { }


This technique is called "initialisa tion of base classes", not
"calling constructors explicitly". Please do not confuse others.
Constructors cannot be called.

Victor


Ok.

-Dhruv.




Jul 19 '05 #8

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

Similar topics

3
50363
by: Phil Powell | last post by:
<?php class SuperClass { var $mySuperClassVar; function SuperClass($myVar) { $this->mySuperClassVar = $myVar; echo "super class var = $myVar<p>"; }
2
2549
by: Michael P. Soulier | last post by:
Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm getting an error. The docs say: A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg)
6
4985
by: cppaddict | last post by:
Hi, I know that C++ does not have an explicit super() constructor for calling a Base class constructor from a Derived class's constructor, but my understanding is that C++ implements this functionality via its initialization list. Say I have a Base class with a constructor that looks like: Base::Base(int x) {
4
2758
by: Alex Hunsley | last post by:
I've seen a few discussion about the use of 'super' in Python, including the opinion that 'super' should only be used to solve inheritance diamond problem. (And that a constructor that wants to call the superclass methods should just call them by name and forget about super.) What is people's opinion on this? Does it make any sense?
1
4154
by: Martin | last post by:
Hi, I've got a base/super class with just a default constructor. I want another constructor, but I can't modify the base class, so I created a sub class with a constructor like so: public class MySub:MyBase { public MySub(string val):base() {
0
1226
by: jhhbr549 | last post by:
Need to write a class called Sales that is extends from a super class called Employee. I feel like I am going in the wrong direction. look at this: Here are the specs: static double field values - BEST_COMMISSION, HIGH_COMMISSION, HIGH_SALES, LOW_COMMISSION,LOW_SALES, QUOTA_COMMISION, QUOTA_SALES. I believe I have the main constructor correct? Method - getCommissionRate( )
10
13303
by: Finger.Octopus | last post by:
Hello, I have been trying to call the super constructor from my derived class but its not working as expected. See the code: class HTMLMain: def __init__(self): self.text = "<HTML><BODY>"; print(self.text); def __del__(self): self.text = "</BODY></HTML>"; print(self.text);
6
2142
by: jmarcrum | last post by:
Hi everyone! I'm using a super class (DVD.java) that handles another class (EnhancedDVD.java). I want to pass the "details" of the DVD into the super class DVD.java. The super class contains the Title, RegionCode, Format, and Length of a dummy DVD...let's say..."Forrest Gump." But I can't figure out how to do this and I have 4 errors going on when I compile the two classes. I have a driver that runs the System.out.println's. But I think...
25
1790
by: dylan m. austin | last post by:
Hello list. This is my first message and it's nothing needful but rather playful. I'd just like to hear some thoughts on something I consider to be a curiosity of javascript usage. I've seen a lot of folks looking to implement some kind of super-like functionality in javascript and it's usually baked into some larger effort of emulating classes. However if you really need* that type of functionality why not get it like so: //assuming...
0
10148
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
10002
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
9938
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
9823
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
6643
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
5270
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
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
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.