I've provided an extremely simplified version of the code which reproduces the error.  class Shape {     public:         virtual void func()=0; };  class Circle : public Shape {     public:         Circle() {  }         void func() { } };  class Square : public Shape {     public:         Square() {  }         void func() { } };  int main() {     Circle c;     std::vector&lt;Circle&gt; circs;      std::vector&lt;Shape*&gt; shapes;      shapes.push_back(&amp;c);      circs.push_back(shapes[0]); //ie, the Circle object that was just pushed into the 'shapes' vector.  }   I know that as of right now, this is functionally useless, and that I could just push the Circle object to the vector - however, in keeping with the shape analogy, my project also has triangles, squares, etc. I process data using a function which accepts Shape&amp; as a parameter, so that I can send all shapes to one function, instead of separate functions for each shape. That's besides the point, but gives insight into why I'm doing what I'm doing in the simplified code.   The last line in this code will not work. Could anyone tell me why? Or provide me with a solution/work-around? Is this considered bad programming-style?  EDIT: So I've solved the Object Slicing issue I was having. For anyone with the same issue, look at fgp's answer in the following thread:    I used the following to help allow what I was trying to do (Move a Circle object to a Shape*, compute some things, then push the Circle (which is in the Shape* vector), to its final resting place, a Circle vector:  class Shape { public:     virtual Shape&amp; operator=(const Shape&amp; s) {         assign(s);         return *this;     }      virtual std::string getName() = 0;     virtual         int getEdges() = 0;    protected:     std::string name;     int         edges;      void assign(const Shape&amp; s) {         this-&gt;name = s.name;         this-&gt;edges = s.edges;     } };  class Circle : public Shape { private:     int radius; public:     Circle() { name = "Circle"; edges = 1; }     Circle(int rad) { name = "Circle"; edges = 1; radius = rad; }      virtual Circle&amp; operator=(const Shape&amp; s) {         if (const Circle* c = dynamic_cast&lt;const Circle*&gt;(&amp;s))             assign(*c);         else{             std::cout &lt;&lt; "BAD ASSIGNMENT IN CIRCLE.";                     //THROW ERROR HERE INSTEAD OF THE ABOVE COUT             }         return *this;     }      std::string getName() { return name; }             int getEdges() { return edges; }             int getRadius() { return radius; }            void setRadius(int r) { radius = r; }  protected:     void assign(const Circle&amp; c) {         Shape::assign(c);         this-&gt;radius = c.radius;     }  };  int main() {     std::vector&lt;Shape*&gt; shapes;     std::vector&lt;Circle&gt; circs;     Circle c2(5); //Creates a circle with 5 for the radius.      shapes.push_back(&amp;c2); //Pushing the 5-radius circle into the Shapes* vector     Circle c3; //Creates a circle with default constructor (which does NOT define radius)     c3 = *shapes[0]; //Now, the overloaded assignment operator. Look at Circle::assign(const Shape&amp;) function     circs.push_back(c3); //We push our newly assigned circle to our Circle vector     std::cout &lt;&lt; "c3 radius: " &lt;&lt; circs[0].getRadius(); //This will be 5! }   It was a pleasant surprise to see this work! c3 will now know about c2's radius, showing that the overloaded assignment operators work for a Shape->Circle conversion.  If anyone has some suggestions, please let me know! (I will be creating a Circle constructor that takes a (const Shape&amp;) param, so I can use Circle c = *shapes[0], instead of having to separate the lines since it cannot find a constructor that accepts that parameter).   EDIT2: Also, if you use this, make sure you throw an error (I left a comment where you should).
664
Someone mentioned it in the IRC as the slicing problem.
36729
I am trying to pass a member function within a class to a function that takes a member function class pointer.  The problem I am having is that I am not sure how to properly do this within the class using the this pointer.  Does anyone have suggestions?  Here is a copy of the class that is passing the member function:  class testMenu : public MenuScreen{ public:  bool draw;  MenuButton&lt;testMenu&gt; x;  testMenu():MenuScreen("testMenu"){     x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&amp;this-&gt;test2);      draw = false; }  void test2(){     draw = true; } };   The function x.SetButton(...) is contained in another class, where "object" is a template.  void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) {      BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);      this-&gt;ButtonFunc = &amp;ButtonFunc; }   If anyone has any advice on how I can properly send this function so that I can use it later.
81430
Does every object of virtual class have a pointer to vtable?  Or only the object of base class with virtual function has it?  Where did the vtable stored? code section or data section of process?
104128
I sometimes notice programs that crash on my computer with the error: "pure virtual function call".  How do these programs even compile when an object cannot be created of an abstract class?
5040
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.   Here is what I did from my constructor:  m_cRedundencyManager-&gt;Init(this-&gt;RedundencyManagerCallBack);   This doesn't compile - I get the following error:      Error  8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&amp;CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member   I tried the suggestion to use &amp;CLoggersInfra::RedundencyManagerCallBack - didn't work for me.   Any suggestions/explanation for this??  I'm using VS2008.  Thanks!!
82117
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared:  class Base {     virtual Base* clone() const = 0; };  class Derived : public Base {     virtual Derived* clone() const };   The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived.  It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following:  class Base {    virtual std::auto_ptr&lt;Base&gt; clone() const = 0; };  class Derived : public Base {     virtual std::auto_ptr&lt;Derived&gt; clone() const; };   Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override.  So, it seems I am left with two options:   Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it. Have clone() return a smart base pointer, and have clients use dynamic_cast to save them to a Derived pointer if they need it.   Is one of these approaches preferred?  Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?
3226
class String {      private:         char* rep;      public:         String (const char*);         void toUpper() const; };   String :: String (const char* s) {     rep = new char [strlen(s)+1];     strcpy (rep, s); }   void String :: toUpper () const {     for (int i = 0; rep [i]; i++)     rep[i] = toupper(rep[i]); }   int main () {     const String lower ("lower");     lower.toUpper();      cout &lt;&lt; lower &lt;&lt; endl;     return 0; }
118197
In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
94655
I was experimenting with C++ and found the below code as very strange.   class Foo{ public:     virtual void say_virtual_hi(){         std::cout &lt;&lt; "Virtual Hi";     }      void say_hi()     {         std::cout &lt;&lt; "Hi";     } };  int main(int argc, char** argv) {     Foo* foo = 0;     foo-&gt;say_hi(); // works well     foo-&gt;say_virtual_hi(); // will crash the app     return 0; }   I know that the virtual method call crashes because it requires a vtable lookup and can only work with valid objects.   I have the following questions    How does the non virtual method say_hi work on a NULL pointer? Where does the object foo get allocated?   Any thoughts?
113807
Why does the following code not work?  I want to instantiate prefabs in a list and then use  it as a GameObject like that :  public GameObject prefab;  void Start() {   ArrayList players = new ArrayList();    for(int i=0; i&lt;5; i++)   {         players.Add( (GameObject)Instantiate(prefab));   }    players[2].transform.position = new Vector3(1, 1, 1);  }   there is an error message
62585
Given the following example, why do I have to explicitly use the statement b-&gt;A::DoSomething() rather than just b-&gt;DoSomething()?  Shouldn't the compiler's overload resolution figure out which method I'm talking about?  I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)  class A {   public:     int DoSomething() {return 0;}; };  class B : public A {   public:     int DoSomething(int x) {return 1;}; };  int main() {   B* b = new B();   b-&gt;A::DoSomething();    //Why this?   //b-&gt;DoSomething();    //Why not this? (Gives compiler error.)   delete b;   return 0; }
8017
I often find myself in a situation where I am facing multiple compilation/linker errors in a C++ project due to some bad design decisions (made by someone else :) ) which lead to circular dependencies between C++ classes in different header files (can happen also in the same file). But fortunately(?) this doesn't happen often enough for me to remember the solution to this problem for the next time it happens again.  So for the purposes of easy recall in the future I am going to post a representative problem and a solution along with it. Better solutions are of-course welcome.     A.h  class B; class A {     int _val;     B *_b; public:      A(int val)         :_val(val)     {     }      void SetB(B *b)     {         _b = b;         _b-&gt;Print(); // COMPILER ERROR: C2027: use of undefined type 'B'     }      void Print()     {         cout&lt;&lt;"Type:A val="&lt;&lt;_val&lt;&lt;endl;     } };       B.h  #include "A.h" class B {     double _val;     A* _a; public:      B(double val)         :_val(val)     {     }      void SetA(A *a)     {         _a = a;         _a-&gt;Print();     }      void Print()     {         cout&lt;&lt;"Type:B val="&lt;&lt;_val&lt;&lt;endl;     } };       main.cpp  #include "B.h" #include &lt;iostream&gt;  int main(int argc, char* argv[]) {     A a(10);     B b(3.14);     a.Print();     a.SetB(&amp;b);     b.Print();     b.SetA(&amp;a);     return 0; }
65196
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream classes don't take a std::string in their constructor or open methods. Everyone loves code examples so:  #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt;  int main() {     std::string filename = "testfile";           std::ifstream fin;      fin.open(filename.c_str()); // Works just fine.     fin.close();      //fin.open(filename); // Error: no such method.     //fin.close(); }   This gets me all the time when working with files. Surely the C++ library would use std::string wherever possible?
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
203
I came across this code:  void f(const std::string &amp;s);   And then a call:  f( *((std::string*)NULL) );   And I was wondering what others think of this construction, it is used to signal that function f() should use some default value (which it computes) instead of some user provided value.  I am not sure what to think of it, it looks weird but what do you think of this construction?
80465
I'm creating a game where I have an Entity class that contains basic entity info (pos, health,..) and some functions. Enemies and Player later on inherit from this class.   Public class Entity {  public Vector2 position; public float health; ,...   Lets say that I have a function like this inside the Entity class:  public GameObject movingIntoEnemy(Vector2 movingToPoint) {     foreach (GameObject go in GameObject.Find("GameMap").GetComponent&lt;GameMap&gt;().enemyList)     {         if (go.GetComponent&lt;EnemyScript&gt;().enemy.position == movingToPoint)         {             return go;         }     }     return null; }   This function looks for a GameObject called "GameMap" and then cycles through enemies in it's list. If an enemy is found, it returns it's GameObject. Using GameObject.Find() is pretty ineffective, so what would be a better approach to this? I mean, I can't just easily use  public GameObject GameMap;   since the code is in a class, and this class needs to be instantiated first in my player/enemy scripts.  My question is - how do I attach gameObjects to this class before it is even created? What is the appropriate approach to this? I guess that I might pass these GameObjects to the class through it's constructor, but it would make things much more complicated.   Thanks in advance ;)
43864
The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc &amp; g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):  char **a; const char** b = a;   I can understand and accept this. The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness ().  char **a; const char* const* b = a;   However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast?  To clarify: 1) Why does this generate a warning in C?  It should be entirely const-safe, and the C++ compiler seems to recognize it as such. 2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function:  void f(const char* const* in) {   // Only reads the data from in, does not write to it }   And I wanted to invoke it on a char**, what would be the correct type for the parameter?