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

Home Posts Topics Members FAQ

Storing downcast objects in a vector

Is it possible to new an object A, downcast it to B, and store B in a
vector?
I'm having problem with the following code:
B is a derived class of A

Blist.push_back ( new B() );
Blist.push_back ( new B() );

A *a = new A();
B *b = static_cast<B*> (a);
B->setProperty(.. .);

Blist.push_back ( new B() ); <- throws heap exception

There is only one memory allocation which is when creating a.
B->setProperty only sets primitive variables. But everytime when I
have B->setProperty enable, the program will crash on the third
push_back. In this example, I'm not even storing b in the list but a
new B.

Is there something wrong with this design? Is it impossible to store a
downcast obj after setting its members in the derived class?

Thanks,
Chester
Jul 22 '05 #1
2 3101
Chester wrote:
Is it possible to new an object A, downcast it to B, and store B in a
vector?
I'm having problem with the following code:
B is a derived class of A

How is Blist defined ?
Blist.push_back ( new B() );
Blist.push_back ( new B() );

A *a = new A();
Ok - You create a pointer to an object of type A.

B *b = static_cast<B*> (a);
Did u really want static_cast here / or did
you mean dynamic_cast. The compiler
would just obey you. But b is not pointing to an
object of type B , since you have not created one till now.

B->setProperty(.. .);
Did you mean b->setProperty here ?

Even if that is the case, you are getting into
*UB* - undefined behaviour - since you have forced
the compiler to make an invalid cast before.
You have not allocated an object of type B before in your
code. How can you make this access anyway.


Blist.push_back ( new B() ); <- throws heap exception
Did you mean -
Blist.push_back ( b ); ??

Please post compilable code-fragment .

There is only one memory allocation which is when creating a.
B->setProperty only sets primitive variables. But everytime when I
have B->setProperty enable, the program will crash on the third
push_back. In this example, I'm not even storing b in the list but a
new B.

Is there something wrong with this design? Is it impossible to store a
downcast obj after setting its members in the derived class?


May be you want dynamic_cast that would help your problems.
And just to add,

A * a = new A;
B * b = dynamic_cast<B *>(a) ; // would fail fail
// i.e. b would be 0 .
// you can use assert to check it .

A * a = new B;
B * b = dynamic_cast<B *>(a) ; // ok - runtime would be happy.
--
Karthik. http://akktech.blogspot.com .
'Remove _nospamplz from the address to get the real one.'
Jul 22 '05 #2
Chester wrote in news:c0******** *************** ***@posting.goo gle.com in
comp.lang.c++:
Is it possible to new an object A, downcast it to B, and store B in a
vector?
I'm having problem with the following code:
B is a derived class of A

Blist.push_back ( new B() );
Blist.push_back ( new B() );

A *a = new A();
B *b = static_cast<B*> (a);
This is Undefined Behaviour(tm), it may work on your implementation
but then again it may cause *anything* to happen (as far as Standard C++
is concerned).
B->setProperty(.. .);
Did you mean b->stProperty() , anyway more UB on top of UB, anything
can happen.

Blist.push_back ( new B() ); <- throws heap exception

What is Blist, is it std::vector< B * >, if so I don't see why
you get a heap exception here, other than you've already violated
Standard C++ rules and have UB anyway (but see below too).
There is only one memory allocation which is when creating a.
Well std::vector does memory allocation and object construction
and copying when you call push_back().
B->setProperty only sets primitive variables. But everytime when I
have B->setProperty enable, the program will crash on the third
push_back. In this example, I'm not even storing b in the list but a
new B.
When you call b->setProprty() , you treat an A object as if it was a
B object probably corrupting the heap. This is just UB manifesting
itself.

Is there something wrong with this design? Is it impossible to store a
downcast obj after setting its members in the derived class?


You should only "downcast" an object that is genuine object of the
derived type, i.e. one that is the result of a prior "upcast".

struct A {};
struct B : A {};

void f( A *a, bool its_really_a_B )
{
if ( its_really_a_B )
{
B *b = static_cast< B * >( a );
// can now use a as a B*.
}
}

int main()
{
A a;
B b;
f( &a, false );
f( &b, true );
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #3

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

Similar topics

17
2589
by: tuvok | last post by:
How can objects of different types be stored in a collection? For example: struct S1 { /*...*/ }; struct S2 { /*...*/ }; struct Sn { /*...*/ }; template<typename T> class X { public:
6
2564
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
12
3935
by: Alfonso Morra | last post by:
I have the ff code for testing the concept of storing objects: #include <vector> #include <iostream> using namespace std ; class MyClass { public: MyClass(){
13
2798
by: r.z. | last post by:
I logged construtor and destructor calls for one of my classes and I discovered that the constructor was called only once while the destructor was called 3 times for a single object. I have a vector of objects of class A: vector<Avector_of_As; and I put objects to it like this: vector_of_As.push_back( A() );
10
2708
by: Jess | last post by:
Hello, I have a program that stores dynamically created objects into a vector. #include<iostream> #include<vector> using namespace std;
3
1680
by: Ramon F Herrera | last post by:
Newbie alert: I come from C programming, so I still have that frame of mind, but I am trying to "Think in C++". In C this problem would be solved using unions. Hello: Please consider the snippet below. I have some objects which are derived (subclassed?, subtyped?) from simpler ones, in increasing size. There is a linear hierarchy. I need to keep them all in some sort of linked list (perhaps std::vector). I could have several
10
3590
by: Dom Jackson | last post by:
I have a program which crashes when: 1 - I use static_cast to turn a base type pointer into a pointer to a derived type 2 - I use this new pointer to call a function in an object of the derived type 3 - this function then 'grows' the derived type object (by pushing onto a vector).
3
1387
by: Bruno.DiStefano | last post by:
Hi All, BACKGROUND INFO I need to use a "vector" structure to store a number of objects that becomes known only at run time. The constructor, at instantiation time of a new object, increments a static counter. The value of this counter becomes the ID of the object that has just been instantiated. I am using Visual C++ 6.0 and, for this project, in the short term I have no options about this.
4
1467
by: alexjcollins | last post by:
The following program demonstrates the problem: #include <vector> #include <iostream> #include <tvmet/Vector.h> typedef tvmet::Vector<double, 3Vector3d; class Mesh {
0
8403
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
8316
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
8833
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
8737
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
8509
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
8610
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...
1
6174
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
5636
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
4168
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...

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.