473,657 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

:: Scope qualifier misunderstandin g.

Hello, I'm relatively new to C++ so I hope you can help clear up a
problem. You may well be able to do so before checking the example, so
don't be put off by the long post :) The problem regards the usage and
effect of the :: scope qualifier. I'm converting a Java app to C++ and
need to find the equivalent of using the Java 'super' keyword. This
executes the 'superclass's constructor (with possibly different
arguments from the derived constructor). I thought I would do this by
using the C++ :: operator, to pick the required base constructor from
within the derived class. Eg,

DerivedClass::D erivedClass(int x)
{
BaseClass::Base Class(x , NULL, NULL); // Call different
constructor.
}

I was hoping this would set the values in the derived class using the
base constructor.

This compiles fine, but any operation carried out in the base class
seem to have no effect on the dervied class. Does anyone know why this
is, and how to remedy this? I've enclosed an example.

The program has 3 classes, base1, base 2 (inherits base 1) and derived
(inherits base2). Each class has one int (b1,b2 and d respectively).

Using :: to call methods to set values b1 and b2 in base1 and base2
has no effect, leaving the values undefines inthe derived class.
The program outputs -842150451 -842150451 3 for the 3 values, instead
of the expected 1,2,3.

I would really appretiate any help with my misunderstandin g,

Regards,

Steve.
// EXAMPLE CODE.

// Base 1 declaration.

class base1
{
public:
base1(){}; // Default constructor.
base1(int);
int b1;
};

base1::base1(in t i)
{
b1 = i;
}

// Base 2 declaration, uses base1 as base class.

class base2 :public base1
{
public:
base2(){}; // Default constructor.
base2(int);
int b2;
};

base2::base2(in t i)
{
b2 = i;
base1::base1(1) ;
}

// Derived class, uses base2 (and therefore class1) as base classes.

class derived : public base2
{
public:
derived(int);
int d;
};

derived::derive d(int i)
{
d = i;
base2::base2(2) ;
}

void main(int argc,char *argv[])
{
derived *d;

d = new derived(3);
printf("%d %d %d ",d->b1,d->b2,d->d);
}
Jul 22 '05 #1
2 4918
Le samedi 28 août 2004 à 09:52:55, bardos a écrit dans comp.lang.c++*:
Hello, I'm relatively new to C++ so I hope you can help clear up a
problem. You may well be able to do so before checking the example, so
don't be put off by the long post :) The problem regards the usage and
effect of the :: scope qualifier. I'm converting a Java app to C++ and
need to find the equivalent of using the Java 'super' keyword. This
executes the 'superclass's constructor (with possibly different
arguments from the derived constructor). I thought I would do this by
using the C++ :: operator, to pick the required base constructor from
within the derived class. Eg,

DerivedClass::D erivedClass(int x)
{
BaseClass::Base Class(x , NULL, NULL); // Call different
constructor.
}

I was hoping this would set the values in the derived class using the
base constructor.

This compiles fine, but any operation carried out in the base class
seem to have no effect on the dervied class. Does anyone know why this
is, and how to remedy this? I've enclosed an example.


I think you want:

DerivedClass::D erivedClass(int x)
: BaseClass(x , NULL, NULL) // Call different constructor.
{
// rest of init there.
}

derived::derive d(int i)
: base2(2)
{
d = i;
}

--
___________ 2004-08-28 10:22:59
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
Jul 22 '05 #2
bardos <> wrote:
I'm converting a Java app to C++ and need to find the equivalent of
using the Java 'super' keyword. This executes the 'superclass's
constructor (with possibly different arguments from the derived
constructor).
In C++, the base class constructors all get called automatically,
before the body of the derived class constructor is executed:
DerivedClass::D erivedClass(int x)
{
By this point, the base class constructors and the member objects
have all been initialized already.
BaseClass::Base Class(x , NULL, NULL);
Actually this creates a new un-named object of type BaseClass,
which is then destroyed immediately. It is similar to:

BaseClass foo(x, NULL, NULL);
}

I was hoping this would set the values in the derived class using the
base constructor.
You need to specify arguments for the base class constructors before
the opening { of the derived constructor (if you don't, then the default
constructors will be called). In fact you can specify initialization
for any member objects and/or base classes at this point:

DerivedClass::D erivedClass(int x)
: BaseClass(x, NULL, NULL), member_int(5)
{
// EXAMPLE CODE.

class base1
{
public:
base1(){}; // Default constructor.
This semicolon isn't required (some people would say, the code is
easier to read without it).
base1(int);
int b1;
};

base1::base1(in t i)
{
b1 = i;
}
Preferable is:
base1::base1(in t it)
: b1(i)
{
}

(Practically speaking, there is no difference, but if 'b1' had been
a class type with a constructor, then your way would have
constructed 'b1' with the default constructor first, and then
assigned 'i' to it: a waste of time).
base2::base2(in t i)
{
b2 = i;
base1::base1(1) ;
}
Similarly:

base2::base2(in t i)
: base1(1), b2(i) {}

Note that the base classes get initialized before the member objects,
regardless of what order you list things here, ie. that would have
been the same as:
: b2(i), base1(1) {}
void main(int argc,char *argv[])
main() must return an int in C++ (many compilers would refuse to
compile your example)
{
derived *d;

d = new derived(3);
printf("%d %d %d ",d->b1,d->b2,d->d);


Coming from a Java background you may be unaware that in C++ you
can create objects with: "Type name(args);" , you should avoid
using "new" if possible. If you "new" an object you have to
"delete" it later, but if you create it with the "Type name(args)"
form, then it is automatically deleted when it goes out of scope.

Also, C++ programs should end their output with a newline.

int main()
{
derived d(3);
printf("%d %d %d \n", d.b1, d.b2, d.d);
// or: std::cout << d.b1 << " " << d.b2 << " " << d.b3 << "\n";
}
Jul 22 '05 #3

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

Similar topics

3
2302
by: Matt Knepley | last post by:
I must be misunderstanding how Python 2.3 handles lexical scoping. Here is a sample piece of code: def run(): a = 1 def run2(b): print a run2(2) print a run()
4
1976
by: Mahesh Tomar | last post by:
Dear Readers, I am porting my existing C code to C++. In my existing code there are numerous functions that has been defined with CONST qualifier. For eg. foo(const DATA_TYPE *x); DATA_TYPE is some typedef structure and offcourse x is a pointer to it. Needless to say my intention for writing such functions in C was to protect the accident write to x's content. So far so good. While porting to C++, I've mada DATA_TYPE as class and I want...
13
2487
by: matthias_k | last post by:
Hi, I've never thought about this before, but since you are able to overload a function only by changing the const-ness of the formal parameters, some annoying side effects will arise. For example, if you only have this code ... void foo( const int n ) {}
7
1507
by: Charles Sullivan | last post by:
On my system (using gcc) I found I need to use the "volatile" qualifier to limit compiler optimization. I notice that this qualifier is described in K&R 2nd edition (1988) but not in K&R 1st edition (1978). Are there realistically any major C compilers in use today that don't recognize this qualifier? Thanks for your help and forbearance.
5
2266
by: strawberry | last post by:
In the function below, I'd like to extend the scope of the $table variable such that, once assigned it would become available to other parts of the function. I thought 'global $table;' would solve this but it's clear that I'm misunderstanding $variable persistence. I posted a similar enquiry over at alt.php.mysql, but I guess this is a more appropriate forum because the problems I'm having relate to PHP. Any help appreciated. ...
7
1182
by: edamron | last post by:
I'm going through a web cast series and have discovered that I have a profound lack of understanding when it comes to the scope of object created in the Load Sub of forms. The instructor creates many objects in the Load event handler. However isn't it true that when the Load sub exits these object will be destroyed?? I don't see how what he is doing can possibly work. Below is the Load handler. Please notice that although he creates...
3
1431
by: =?Utf-8?B?U2N5dGhlbg==?= | last post by:
Hi all, I have some code similar to the following: C# MyClass mVer = ne w MyClass(); …in a member function mVar.SendEvent( new Event() );
4
2222
by: Ben Petering | last post by:
Hi group, this is a 'best practice' type question (I want discussion of the issue - whys and why nots - similar to "casting the return value of malloc()", to cite an analogous case). Let's say I have a function written in assembler/(some non-C language) which takes one pointer-to-const-char arg, the declaration being: extern unsigned int str_len(const char *s);
3
2474
by: John Dann | last post by:
Trying to learn Python here, but getting tangled up with variable scope across functions, modules etc and associated problems. Can anyone advise please? Learning project is a GUI-based (wxPython) Python program that needs to access external data across a serial port. The first thing that I need the program to do when it starts up is to check that it can see the serial port, the first step of which is to check that it can import the...
0
8421
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
8325
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
8518
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,...
1
6177
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
5643
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
4173
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
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1971
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1734
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.