C++Guns – RoboBlog

06.09.2011

example to change the base instance of a derived object

Filed under: Allgemein — Tags: , , — Thomas @ 15:09

Man hat ein Array von Objekten einer abgeleiteten Klasse.
Da new[] nur den Default Konstruktor aufruft, kann man keine schon existierende Instanz der Basisklasse mitgeben.
Folgender Code zeigt, wie man die Basisinstnaz nachträglich ändern kann.


// example to change the base instance of a derived object
#include < iostream >
using namespace std;

class rawData
{
public:
double x;
};

class extendedData : public rawData
{
public:
int a;
};

int main ()
{
rawData *knoten = new rawData[2];
knoten[0].x = 0;

extendedData *knotenext = new extendedData[2];
knotenext[0].x = 1;
knotenext[0].a = 10;

cout << knotenext[0].x << endl; cout << knotenext[0].a << endl; // do the magic rawData *base = &knotenext[0]; *base = knoten[0]; cout << knotenext[0].x << endl; cout << knotenext[0].a << endl; delete[] knoten; delete[] knotenext; return 0; }

Ausgabe:

1
10
0
10

Valgrind:

kater@mintux:~$ valgrind ./a.out --leak-check=full
==7218== Memcheck, a memory error detector.
==7218== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==7218== Using LibVEX rev 1854, a library for dynamic binary translation.
==7218== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==7218== Using valgrind-3.3.1-Debian, a dynamic binary instrumentation framework.
==7218== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==7218== For more details, rerun with: -v
==7218==
1
10
0
10
==7218==
==7218== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 18 from 1)
==7218== malloc/free: in use at exit: 0 bytes in 0 blocks.
==7218== malloc/free: 2 allocs, 2 frees, 40 bytes allocated.
==7218== For counts of detected errors, rerun with: -v
==7218== All heap blocks were freed -- no leaks are possible.

Eigentlich hätte ich erwartet, dass man das alte Basisobjekt noch löschen muss. Aber anscheinend nicht :)

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

You must be logged in to post a comment.

Powered by WordPress