Saturday, May 9, 2009

(C++) How can I get the size of an object from a pointer to a base class?

class Class{


public:


int Something;


};





class DerClass : public Class{


public:


int Array[256];


};





main()


{


Class*C = new DerClass;


sizeof(*C); // = 4


sizeof(DerClass); // = 1028


}





// How can I get 1028 from pointer C?

(C++) How can I get the size of an object from a pointer to a base class?
As far as I know, in c++ it is impossible to get the size of an object just from the base class and sizeof function. One way to get around this is to use dynamic_cast as follows.








struct A {


int a;


virtual ~A() {}


};





struct B : public A {


int b[128];


virtual ~B() {}


};





struct C : public A {


int c[256];


virtual ~C() {}


};





size_t sizeofA(A* a) {


if (dynamic_cast%26lt;C*%26gt;(a))


return sizeof(C);


else if (dynamic_cast%26lt;B*%26gt;(a))


return sizeof(B);


else


return sizeof(A);


}
Reply:sizeof() hard codes size of objects into the program at compile time. Allocated (ie: 'new') memory block sizes are unknown until run time, making sizeof() hopeless to help.





So, don't think it can be done via pointer.


I need some help with C++ pointer operators.?

I have a question about C++ pointer operators. What's the difference between these two operators, .* and -%26gt;*, and . and -%26gt;? I know what the dot does, but I'm not so sure about the rest of them, specifically the pointers-to-members operators. (I know they're names and Microsoft tries to explain them but it's a little confusing.) Help? Thanks.

I need some help with C++ pointer operators.?
okay. you said you know the dot operator, then, the -%26gt; operator works just the same. Except, the -%26gt; calls the member of the pointer objects. for eg, you have declared one instant of the class such as:





Student *mystudent;





where the mystudent object has become the pointer to the class Student.


Just because of this, whenever you want to access the Student class member, you need to use the -%26gt; instead of . operator, like in this line:





mystudent-%26gt;getStudent();











The same for ......-%26gt;*.......,


this really returns the pointer(i.e address) of the corresponding member being called, like in this case,





mystudent-%26gt;*getStudent();





will return the address of the getStudent value, which is stored in the system.
Reply:dude i really dont know. i only know about C

online survey

What is the output of C++ pointer variables with cout?

Consider the following program:





#include %26lt;iostream%26gt;





using namespace std;





void f(char* %26amp;c);


void g(char* myString);





int main()


{


char myString[10] = "Midterm";


char *tempPtr;





tempPtr=myString;


cout %26lt;%26lt; myString %26lt;%26lt; endl;


cout %26lt;%26lt; tempPtr %26lt;%26lt; endl;


g(myString);


g(tempPtr);


f(tempPtr);


cout %26lt;%26lt; myString %26lt;%26lt; endl;


cout %26lt;%26lt; tempPtr %26lt;%26lt; endl;


return 0;


}





void f(char* %26amp;s)


{


s=s+3;


cout %26lt;%26lt; s %26lt;%26lt; endl;


}





void g(char* myString)


{


myString=myString+5;


cout %26lt;%26lt; myString %26lt;%26lt; endl;


}





On gnu compilers, this is the output:





Midterm


Midterm


rm


rm


term


Midterm


term





Now, my question is, are there any implementations of C++ that only output what the pointer variable is pointing to? (i.e. not including the the following characters of the array?)





For example, are there any implementations that would make this be the output:





Midterm


M


rm


r


t


Midterm


t





Any light on how pointer variables are output will be appreciated!!!

What is the output of C++ pointer variables with cout?
No, cout will always print all the characters of char*'s until it hits a null.





You need to dereference the char* to an individual character before cout'ing it to get what you want:





char str[10] = "Midterm";


cout %26lt;%26lt; *(str+3) %26lt;%26lt; endl; // This outputs 't'
Reply:No.





And while cout function is included with most compilers it is NOT part of the language, but just a library of standard code people find useful to use.


(eg I can use c/c++ to code for my nokia phone but as there a gui and no commandline there no cout function provided in the dev kit!)





You need to change your code not the compiler of course!!! Just tested and MS Compiler gives same results, as you should expect!





C/C++ work with null terminated strings. And arrays are treated in many ways as little more than your tempPtr pointer.





So you reserved 10 bytes for your string, the first 7 chars are the letters then theres a 0/null byte, and the next 2 bytes are uninitilised(we cant be sure what values they could take at runtme.





Now cout treats any pointer to or array of chars the same it output the charaters in the order it finds them until it comes to a null valued byte. if we initialse out array as say {M','i','d','t','e','r','m'} we'd need to add a ,0 or cout would just keep going through memory writing what if finds until it eventually finds a zero or the program crashes(the OS should throw an exception if tries to read outside the part of memory given to your program)





If given a char though not a pointer to a char then it'll give just that char.





Eg.


cout *(myString+1);


prints only the letter "i"


and


cout %26amp;myString;


shows the memory address used for myString.





Remember the referencing and dereferencing operators?





Wait - but for more than one char to be output but not the whoile string you need a suitably sized buffer(the final substring size + 1 char for the null) and would memcopy the bytes into it and the set a null at the end before sending it to cout.


Some C++ pointer and dynamic memory help please!? How do I delete a struct?

I am trying to make a linked data type in C++ which acts like array, but is a linked structure made up of nodes, where each node knows the next and previous node, there for linking it.





so say I had a linked data type of X, ( I am doing this in a class), how do I delete a node?





EX;





template %26lt;class Type%26gt;


struct a{





Type data;





Node* nextNode;


Node* previousNode;





};





template %26lt;class Type%26gt;


class list{


public:


void insert();


void remove();





private:


Node%26lt;Type%26gt;* frontOfList;


usigned int size;


};








template %26lt;typename Type%26gt;


void Stack%26lt;Type%26gt;::remove()


{





// the front pointer does not point to a next pointer because it


//is the front so it is null


front-%26gt;previousNode-%26gt;nextNode = NULL;





Node%26lt;Type%26gt;* temp = front;








delete front;





// is this deleting the pointer front?


//or actually the node the front points to, and deleting the data, and the pointers to the next and previous node?





front = temp-%26gt;previousNode;








delete temp;


--size;


}








void X::insert(){


-


adds an element to the front of arr

Some C++ pointer and dynamic memory help please!? How do I delete a struct?
The easy answer to your question is to use STL lists. They do exactly what you want and are efficient and reliable. But that doesn't help you do it for a class.





The way you're implementing this, you don't ever want to delete the item itself. This is because your list structure has a copy of the item (Type data) instead of a pointer to the data (Type * data). If you do it this way (the hard way), you will want to use the following algorithm:





1. When inserting an item into your list, create a new element (a * listItem = new a) then copy the data in (a.data = dataToInsert). If you want to support lists of items with non-default constructors you should do both in one line (a * listItem = new a(dataToInsert)) which means you'll want a constructor for your class that takes a reference to the new data.





2. Insert the item into the list.





3. When removing, don't try to delete data. You can't. Delete the whole thing (delete listItem) once you're sure no previous or next pointers are pointing to it.





An easier way is to make data a pointer to your type. (Type * data instead of Type data). In this case, you'd follow the algorithm above with the following differences: First, it's easier to create a link item because you don't have to worry about whether you can create an empty data object. Create the item, then create a new data object using the copy constructor (this is important, otherwise you don't know when it's safe to delete it later. Create a copy, then you can delete it whenever you need). Second, before you delete your struct, delete the data it holds.





Incidentally, if you are creating a stack (only adding/removing from the front), there's no need for a doubly-linked list. You only need a "next" pointer. Add and remove from the head.





Here's a 25-cent overview of new and delete:


1. When you allocate memory by using new, you are responsible for deleting it. The corrolary of that is, never use delete on something you didn't "new", such as a local variable.


2. Never delete an object that something is still pointing to


3. Never delete something twice


4. Never reference memory you've deleted


5. If you allocate using new[] (for allocating arrays) delete using delete[].





Good luck.
Reply:Ok, you can find a good description of linked lists here:





http://www.inversereality.org/tutorials/...





It highlights every aspect including deleting.
Reply:templates are difficult concept. may be you can contact a C++ expert. Check websites like http://askexpert.info/


Difficult C++ pointer question, PLEASE HELP!!!!?

I'm reading this tutorial on c++, apparently when you define a pointer to be const, the address of that pointer can not be changed. However the below code defines a pointer as const called pointer and points to the address of variable a1, however i then give the pointer a new address (variable a2). I'm really confused because point was declared as a constant, yet a can change the address of the pointer and the program compiles with out any errors. can any body explain to whats happening and y my theory isn't working?





#include%26lt;iostream%26gt;


int main()


{


int a1 = 1, a2 = 2;


int const *point = 0;


point = %26amp;a1;


std::cout%26lt;%26lt;*point%26lt;%26lt;'\n';


point = %26amp;a2;


std::cout%26lt;%26lt;*point%26lt;%26lt;'\n';


system("pause");


return 0;


}





output:


--------


1


2


press any key to continue........

Difficult C++ pointer question, PLEASE HELP!!!!?
the compiler interprets


int const *point


as


const int *point


which mean it is a pointer to a constant integer.


change it to


int * const point


will cause the pointer point to not be changed.
Reply:The correct syntax for a constant pointer (that is a pointer that is constant itself rather than a pointer that points to a constant) would be:-





int* const point
Reply:The thing pointed to by the pointer is considered constant.
Reply:i asked the same question to myself just the other day, i worked on the problem for a week and resolved it but then i was diagnosed with a rare form of degenerative brain stem deterioration and i have short term memory loss as a result, but i knew i worked this out, i just cant remember so I'll let you know next year
Reply:Its because assigning a value and pointing to a variable are two different things. Its kind of like what the 1st person said.





For ex: point = %26amp;a1;


In this line, point is pointing to the variable a1.





Now try changing the value of a1 USING point.





ex:


*point = 5;


or


*point = 8;


or


*point = a2;





All will generate an error BECAUSE point was declared as a constant. Now try removing const from your declaration, all the above statements should execute correctly.