473,382 Members | 1,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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 3082
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.google.c om 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
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
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...
12
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
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...
10
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
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...
10
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...
3
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...
4
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
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.