0

I make a project to c++ and i need some methods to be virtual in my class.. so When i include in my main.cpp the "class".h , compiler says undefined reference to my method and when i change "class".h to "class".cpp it says first defined in main.o and multiple definition in class.cpp

class Avl {

public:

    Avlnode* insert(unsigned int key , Avlnode *root);
    AvlofAvlnodes* insert(unsigned int key, unsigned int neighbors[],int size, AvlofAvlnodes *id );

    template <typename nodeptr>
    bool findElement(unsigned int element, nodeptr* root);
    bool findConecion(unsigned int id, unsigned int neighbor,AvlofAvlnodes* root);

    Avlnode* deletion(Avlnode* root,unsigned int key );
    void deletion(unsigned int key , unsigned int neighbor,AvlofAvlnodes* root);

    // methods to help avl
    template <typename nodeptr>
    nodeptr* rightRotate(nodeptr* root);
    template <typename nodeptr>
    nodeptr* leftRotate(nodeptr* root);

    int max(int a,int b);
    template <typename nodeptr>
    int height(nodeptr* root);
    template <typename nodeptr>
    int getBalance(nodeptr* root);
    template <typename nodeptr>
    nodeptr* minValueNode(nodeptr* root);
    template <typename nodeptr>
    void preOrder(nodeptr* node);

};
Mat
  • 202,337
  • 40
  • 393
  • 406
Tsam
  • 11
  • 2
  • As a general rule, you should only include .h files and not .cpp files. It is normal practice to put either `#pragma once` or guard `#define`s to prevent the same headers being included more than once. see https://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard – Dragonthoughts May 23 '18 at 13:26

2 Answers2

1

You always include the "class.h", never the "class.cpp". That's because #include is handled during the compilation phase, while the different .cpp files are pieced together in the linking phase. More accurately, each .cpp file is translated into an object file, and those are then linked.

Your missing virtual methods are the result of a missing object file. We know main.cpp is, but is "class.cpp" compiled?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
MSalters
  • 173,980
  • 10
  • 155
  • 350
0

Only include hpp files and then you need to add the cpp file to the compiler. If you are using the command line, it should look like this:

g++ main.cpp class.cpp -o a.out

If you are using a C++ IDE, it will compile the class.cpp file as long is it is part of your project.

A. Cloete
  • 69
  • 6