I am new to C++ and got this error for hours and I hope someone can help me with this.  So basically I have got 2 classes: Matrix,DenseMatrix with DenseMatrix being the subclass of Matrix.    For some simple mathematical operations like adding two matrices which are always the same for any type of matrix, I wanted to implement a function in the class Matrix.   T &amp;mul(const Matrix &amp;other);   The idea is that calling mul on a subclass (e.g DenseMatrix), the result will also be a DenseMatrix. However the other matrix does not need to be the same class, just any subclass of Matrix. That's why I use generic types and my classes are defined like this:  class DenseMatrix : public Matrix&lt;DenseMatrix&gt; class OtherMatrix: public Matrix&lt;OtherMatrix&gt; class OtherMatrix2: public Matrix&lt;OtherMatrix2&gt; ...   So that calling mul will return a matrix of the same type and the argument is simply a Matrix without diamond-brackets.  Now the Problem is that I am getting the following error:  DenseMatrix mat{6,6}; DenseMatrix mat2{6,6}; mat.add(mat2);  &gt;&gt;&gt; undefined reference to `Matrix&lt;DenseMatrix&gt;::add(Matrix&lt;DenseMatrix&gt; const&amp;, int)'   I was thinking that maybe I need to introduce a second generic type for the argument of the function but I am not sure how to do this.  I am very happy if someone could help me with this one.    Matrix.h:  template &lt;typename T&gt; class Matrix {     T &amp;add(const Matrix &amp;other, int threads = 1); }   Matrix.cpp:  #include "Matrix.h" template&lt;typename T&gt; T &amp;Matrix&lt;T&gt;::add(const Matrix &amp;other, int threads) {     std::cout &lt;&lt; "ADDING";     return *this; }   DenseMatrix.h:  class DenseMatrix : public Matrix&lt;DenseMatrix&gt; {   }
341
Quote from :     The only portable way of using templates at the moment is to implement them in header files by using inline functions.   Why is this?  (Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)
42167
The following code:  template &lt;typename S, typename T&gt; struct foo {    void bar(); };  template &lt;typename T&gt; void foo &lt;int, T&gt;::bar() { }   gives me the error  invalid use of incomplete type 'struct foo&lt;int, T&gt;' declaration of 'struct foo&lt;int, T&gt;'   (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:  template &lt;typename S&gt; struct foo {    void bar(); };  template &lt;&gt; void foo &lt;int&gt;::bar() { }   then it compiles correctly.
60879
Can anyone recommend any good resources for learning C++ Templates?  Many thanks.
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
107586
Can a class overload methods that also exist in the publicly inherited interface? It seems like this is unambiguous and useful, but compilers (VC, Intel, GCC) all complain, at least by my construction. Below is a toy example. The inherited rebound() function has two clear overloads, yet this will not compile.  If you rename the rebound() method in either class, it works fine, but if they share the same member function name (even though they're overloaded with different argument types!) you get a fatal error of "too few arguments to function call."  The workaround is trivial (I'll just rename the methods) but I'm just trying to understand if this is a C++ restriction (and why it would be).   #include  class Bound { public:   Bound() : x0(0.0), x1(0.0) {};   Bound(double x) : x0(x), x1(x) {};   double width() const {return x1-x0;}   void rebound(const Bound *a, const Bound *b); private:   double x0, x1; };  void Bound::rebound(const Bound *a, const Bound *b) {   if (a && b) {     x0=std::min(a->x0, b->x0);     x1=std::max(a->x1, b->x1);   } }  class Node : public Bound { public:   Node(double x) : Bound(x), left(0), right(0) {};   Node(Node *a, Node *b) : left(a), right(b) {rebound();}   void rebound() { rebound(left, right); } private:   Node *left;   Node *right; };   int main() {   Node A(1.0);   Node B(2.0);   Node C(&A, &B); }
42622
We all know what virtual functions are in C++, but how are they implemented at a deep level?  Can the vtable be modified or even directly accessed at runtime?  Does the vtable exist for all classes, or only those that have at least one virtual function?   Do abstract classes simply have a NULL for the function pointer of at least one entry?  Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual?  And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
22280
I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.  MyClass *m = (MyClass *)ptr;   all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?  MyClass *m = (MyClass *)ptr; MyClass *m = static_cast&lt;MyClass *&gt;(ptr); MyClass *m = dynamic_cast&lt;MyClass *&gt;(ptr);
81821
In the  library, they are overloading the () operator.  Is this a convention in C++? For callbacks, etc.?  I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.  Any insight as to the reason for this overload?
44161
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking.  What's happening here, and how can I fix it?
19841
I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.  Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.  This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.  So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like   Inscrutable compiler errors in places where you don't expect them? Code bloat?  Difficulty in tracing code? Setting Debugger Breakpoints?
32250
I've looked at , specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example?    What I can make from the answers so far, it seems to me to be just a more complex way of doing this:  have an abstract class: MoveAlong with a virtual method: DoIt() have class Car inherit from MoveAlong,       implementing DoIt() { ..start-car-and-drive..} have class HorseCart inherit from MoveAlong,       implementing DoIt() { ..hit-horse..} have class Bicycle inherit from MoveAlong,       implementing DoIt() { ..pedal..} now I can call any function taking MoveAlong as parm  passing any of the three classes and call DoIt Isn't this what Strategy intents? (just simpler?)   [Edit-update] The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.)    [Edit-update] Conclusion  The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).
16158
Consider this example (typical in OOP books):    I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.  Here's the Animal class:  public class Animal {     private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;();      public void addFriend(String name, Animal animal){         friends.put(name,animal);     }      public Animal callFriend(String name){         return friends.get(name);     } }   And here's some code snippet with lots of typecasting:  Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck());  ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();   Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say      jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack();   Here's some initial code with return type conveyed to the method as a parameter that's never used.   public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){     return (T)friends.get(name);         }   Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this?
118197
In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
15868
Why does this code:  class A {     public:          explicit A(int x) {} };  class B: public A { };  int main(void) {     B *b = new B(5);     delete b; }   Result in these errors:   main.cpp: In function ‘int main()’: main.cpp:13: error: no matching function for call to ‘B::B(int)’ main.cpp:8: note: candidates are: B::B() main.cpp:8: note:                 B::B(const B&)   Shouldn't B inherit A's constructor?  (this is using gcc)
983
I have some template code that I would prefer to have stored in a CPP file instead of inline in the header.  I know this can be done as long as you know which template types will be used.  For example:  .h file  class foo { public:     template &lt;typename T&gt;     void do(const T&amp; t); };   .cpp file  template &lt;typename T&gt; void foo::do(const T&amp; t) {     // Do something with t }  template void foo::do&lt;int&gt;(const int&amp;); template void foo::do&lt;std::string&gt;(const std::string&amp;);   Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.  My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.
16896
I have a generic class that I'm trying to implement implicit type casting for.  While it mostly works, it won't work for interface casting.  Upon further investigation, I found that there is a compiler error: "User-defined conversion from interface" that applies.  While I understand that this should be enforced in some cases, what I'm trying to do does seem like a legitimate case.  Here's an example:  public class Foo&lt;T&gt; where T : IBar {     private readonly T instance;      public Foo(T instance)     {         this.instance = instance;     }     public T Instance     {         get { return instance; }     }     public static implicit operator Foo&lt;T&gt;(T instance)     {         return new Foo&lt;T&gt;(instance);     } }   Code to use it:  var concreteReferenceToBar = new ConcreteBar(); IBar intefaceReferenceToBar = concreteReferenceToBar; Foo&lt;ConcreteBar&gt; concreteFooFromConcreteBar = concreteReferenceToBar; Foo&lt;IBar&gt; fooFromConcreteBar = concreteReferenceToBar; Foo&lt;IBar&gt; fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work   Does anyone know a workaround, or can anyone explain in a satisfactory way why I shuouldn't be able to cast interfaceReferenceToBar implicitly to Foo&lt;IBar&gt;, since in my case it is not being converted, but only contained within Foo?  EDIT: It looks like covariance might offer salvation.  Let's hope the C# 4.0 specification allows for implicit casting of interface types using covariance.
51146
Here is an example of polymorphism from  (edited for readability):  // abstract base class #include &lt;iostream&gt; using namespace std;  class Polygon {     protected:         int width;         int height;     public:         void set_values(int a, int b) { width = a; height = b; }         virtual int area(void) =0; };  class Rectangle: public Polygon {     public:         int area(void) { return width * height; } };  class Triangle: public Polygon {     public:         int area(void) { return width * height / 2; } };  int main () {     Rectangle rect;     Triangle trgl;     Polygon * ppoly1 = &amp;rect;     Polygon * ppoly2 = &amp;trgl;     ppoly1-&gt;set_values (4,5);     ppoly2-&gt;set_values (4,5);     cout &lt;&lt; ppoly1-&gt;area() &lt;&lt; endl; // outputs 20     cout &lt;&lt; ppoly2-&gt;area() &lt;&lt; endl; // outputs 10     return 0; }   My question is how does the compiler know that ppoly1 is a Rectangle and that ppoly2 is a Triangle, so that it can call the correct area() function? It could find that out by looking at the "Polygon * ppoly1 = &rect;" line and knowing that rect is a Rectangle, but that wouldn't work in all cases, would it? What if you did something like this?  cout &lt;&lt; ((Polygon *)0x12345678)-&gt;area() &lt;&lt; endl;   Assuming that you're allowed to access that random area of memory.  I would test this out but I can't on the computer I'm on at the moment.  (I hope I'm not missing something obvious...)