Search code examples
c++headerlinker

Problem with C++ header file and class implementation


first of all thank you to anyone that reads my question and special thanks to anyone that can offer advice.

I’m in the second week of CS 162 right now and our professor has just introduced us to classes. After following along to his code I have been completely unable to compile or use a class that I create.

In an attempt to understand my issue I have created three files: tomato.h, tomato_imp.cpp and tomato_driver.cpp.

as the name suggests tomato.h is the header file that defines a class “tomato”.

tomato_imp is the implementation file and tomato_driver tries to use the functions and definition of tomato to preform a simple operation.

tomato.h:


#ifndef TOMATO
#define TOMATO
 
class tomato
{
private:
    int tweight;
    
 
public:
    tomato(int weight=0);
 
    void setTomato(int weight);
 
    int getTomato() { return tweight}
    
};
 
#endif /*TOMATO*/

tomato_imp.cpp:

#pragma once;
#include "tomato.h"
 
//tomato constructor
tomato::tomato(int weight)
{
  setTomato(weight);
}
 
// tomato member function
void tomato::setTomato(int weight)
{
   tweight=weight;
}

tomato_driver.cpp:

#include <iostream>
#include "tomato.h"

int main(){

    tomato john;

    john(4);

    cout<<tomato::john.getTomato;
}

I am using a MacBook with OS X 10.15.5, I am using g++ to compile my files.

the header file compiles with the warning, clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated [-Wdeprecated].

When I try to compile the implementation file it gives me several errors:

  1. tomato_imp.cpp:5:9: error: redefinition of 'tomato' tomato::tomato(int weight) ^ ./tomato.h:11:2: note: previous definition is here tomato(int weight){}; ^
  2. tomato_imp.cpp:7:3: error: use of undeclared identifier 'setTomato'; did you mean 'tomato'? setTomato(weight); ^ ./tomato.h:5:7: note: 'tomato' declared here class tomato{ ^
  3. tomato_imp.cpp:11:14: error: out-of-line definition of 'setTomato' does not match any declaration in 'tomato' void tomato::setTomato(int weight) ^~~~~~~~~

I’m not sure what’s going on with these errors, all three files are saved in the same folder. I have commented out #pragma once and it still sends the exact same error messages.

This is slightly beyond the realm of Computer Science that I currently understand and any help would be greatly appreciated.


Solution

  • I think that with john(4) you meant to call the setter function; you can replace it with

    john.setTomato(4);
    

    Also, the way you use it later is incorrect, you can do

    std::cout << john.getTomato(); // do not forget ()
    

    Finally you should be able to compile your example with:

    g++ -c tomato_imp.cpp -o tomato_imp.o
    g++ tomato_imp.o tomato_driver.cpp -o tomato
    

    And run it with

    ./tomato