52784

Array memory Allocation doesn't work

Question:

I have the next classes:

class A { }; class B : public A { int num; };

in my main I have:

int main() { A* vec; // A is a class with pure virtual functions vec = new B[2]; // want to create a vector of B }

vec[0] is defined correctly, but vec[1] is NULL. why didn't it allocate me a fit memory?

I don't want to change the lines of the main. just make it working.

(I know I can change the main into: B* vec = new B[2] but I don't want)

any help appreciated!

Answer1:

You cannot treat arrays polymorphically, the C++ language does not support it. The expression vec[x] uses pointer arithmetic to determine the location of the element. If you are accessing it through a base class pointer it will not work if the size of the objects vary in any way.

For example, you have base class that is 4 bytes in size and the subclass is 8 bytes in size.

base *a = new child[4];

When you access a[1] the compiler calculates the offset using the size of the base class. In this case the offset is 4 bytes which ends up pointing to the middle of the first element.

I recommend using a std::vector or std::array of pointers with an appropriate smart pointer.

// For arrays that needs to be resized (requires delete for each new) std::vector<A*> vec(5, NULL); for(int i = 0; i < vec.size(); i++) { vec[i] = new B(); } // for arrays that are fixed in size (requires delete for each new) std::array<A*, 5> vec; for(int i = 0; i < vec.size(); i++) { vec[i] = new B(); } // for arrays that are fixed in size with smart pointers // no delete needed std::array<std::unique_ptr<A>, 5> vec; for(int i = 0; i < vec.size(); i++) { vec[i].reset(new B()); }

Answer2:

if you would like it to be polymorphic just create an array of pointers

new A*[array_size]

Answer3:

This code snippet illustrates the problem you are having.

#include <iostream> using namespace std; class A { }; class B : public A { int num; }; int main() { A* vec; // A is a class with pure virtual functions vec = new B[2]; // want to create a vector of B cout << sizeof(vec) << endl; cout << sizeof(*vec) << endl; cout << sizeof(vec[2]) << endl; cout << sizeof(new B()) << endl; }

In pointer arrithmetic, the size of the type of the pointer you allocated is what is used for incrementing, not the size of the true type of the object it is pointing to. More simply, the language does not support polymorphic arrays. This is simply an explanation of why.

Recommend

  • Array resizing and realloc function
  • const char **a = {“string1”,“string2”} and pointer arithametic
  • Generate a business key
  • How does `std::terminate` know to treat `std::exception`s specially?
  • javascript add operation returns bad result
  • Listview - list item selection and initial setting (custom made items)
  • Java Garbage collection, setting reference to null
  • Recreate the Oracle DUAL table
  • How to determine the CCSID used in CPYFRMIMPF command?
  • force json_encode to create strings
  • Most efficient way to replace lowest list values in dataframe in R
  • How to discover Font Type?
  • Create a link to a web page that runs a Javascript function on the page
  • In C what exactly happens if i use () to initialize a double dimension array instead of the {}?
  • Cut the background to expose the layer below
  • What Makes These Two Array Adds Different?
  • Android device acting as an accessory
  • Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
  • NUnit 3.0 TestCase const custom object arguments
  • Plotting line graph with factors in R
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Object and struct member access and address offset calculation
  • How to assign byte[] as a pointer in C#
  • Z3: Convert between FP and BitVector?
  • gspread or such: help me get cell coordinates (not value)
  • Installing Apache MyFaces 2 on WildFly 8.2.0
  • Hardware Accelerated Image Scaling in windows using C++
  • Custom Tabgroup Appcelerator
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Yii2: Config params vs. const/define
  • The plugin 'org.apache.maven.plugins:maven-jboss-as-plugin' does not exist or no valid ver
  • FFmpeg Conversion Error
  • How to rebase a series of branches?
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Projection media query: browser support and workarounds?
  • Different response to non-authenticated users and AJAX calls
  • Can I make an Android app that runs a web view in Chrome 39?
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • How to include full .NET prerequisite for Wix Burn installer
  • How can i traverse a binary tree from right to left in java?