Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I creating an object correctly in the header file?

So I'm trying to use classes to do a linked list. I've never used classes on c++. What I'm trying to do is simply to create an object of the class palabra on the header file.

I want to access primeraPalabra on the .cpp file for later methods. I am not able to create the object.

The error that I'm getting is: multiple definition of "primeraPalabra".

I'm also new with the use of headers and cpp files. any tip is appreciated.

palabra.h file

#ifndef PALABRA_H_INCLUDED
#define PALABRA_H_INCLUDED

#include <iostream>
using namespace std;


class Palabra{
    private:
    int p_id;
    string p_nombre;
    int p_valor;

    Palabra *next;
    Palabra *prev;


public:
    Palabra(int id, string nombre);
    void printNombre();
    int calcularValorPalabra();

    void agregarSiguiente(Palabra *);
    void eliminar();
    void buscar();
};

Palabra primeraPalabra(0,"");
Palabra ultimaPalabra(0, "");
Palabra palabraTemp(0, "");


#endif // PALABRA_H_INCLUDED

palabra.cpp file

Palabra::Palabra(int id, string nombre)
    {
    p_id = id;
    p_nombre = nombre;
    p_valor = calcularValorPalabra();

    next = NULL;
    prev = NULL;
}
like image 890
Oscar Avatar asked Dec 09 '25 08:12

Oscar


1 Answers

Palabra primeraPalabra(0,"");
Palabra ultimaPalabra(0, "");
Palabra palabraTemp(0, "");

This, in your header file, defines and instantiates three objects. Every .cpp that includes this header file will define these three objects. You obviously have multiple .cpp files; so that's your multiple definition error that your compiler and linker eventually barks at you about.

An #include is logically equivalent to inserting the contents of the header file, verbatim, into the .cpp file. Remove these definitions from the header file, and manually add them to every .cpp file that includes this header file, and you'll get the same error.

You need to declare these objects, using the extern keyword in your header file. Then, define these objects in exactly one of your .cpp files, in whichever one you feel is more appropriate to define them.

Your C++ book should have plenty of examples of doing this kind of a thing, and how to use the extern keyword.

P.S. That using namespace std;, in your header file no less, is going to give you a world of hurt sooner or later. You need to get rid of it. Since, you explain, you're just starting to learn C++, this is the best time for you to avoid picking up bad habits. Simply forget that "using namespace std;" exists in C++, for now, until you fully understand what it does. It may seem irritating, at first, but it won't be long before you won't even be consciously aware of your fingers automatically typing std:: before every template, class, and function from the C++ library.

like image 84
Sam Varshavchik Avatar answered Dec 10 '25 22:12

Sam Varshavchik