Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ classes without .cpp files?

I don't want to write a .cpp file for every simple c++ class.

when I write a class definition and declaration in a single .hpp file, the linker complains about multiple definition of member functions which are not implemented inside the body of the class.

So I use templates to get rid of linker complaints:

// log.hpp file
template<typename T>
class log_t {
private:
    int m_cnt = 0;
public:
    void log();
};

template<typename T>
void log_t<T>::log() {
    std::cout << ++m_cnt << std::endl;
}

// some random type (int)
typedef log_t<int> log;

And then I can simply use log class in multiple .cpp files without linker complaints.

Is there something fundamentally wrong with this method?

Edit: even when i use this method will member functions become inline ?

like image 827
amin Avatar asked Oct 25 '25 21:10

amin


2 Answers

If some class doesn't need to be a template, don't make it a template just to "get rid of the linker's complains". Just use proper coding techniques, like providing inline defintions of member functions:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    log();
};

// Note "inline" here:
inline log::log() {
    std::cout << ++m_cnt << std::endl;
}

If you provide the function's body inside the class definition, then there's no need to specify the keyword inline:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    // Function body inserted here (no need for "inline"):
    log() {
        std::cout << ++m_cnt << std::endl;        
    }
};
like image 75
Mr.C64 Avatar answered Oct 28 '25 11:10

Mr.C64


As you want the functions to be defined in headers (which are included in multiple source files, which leads to multiple definitions in your case), you should make the functions inline.

2 options:

  • implicit inline - do not separate the function definitions
  • explicit inline - manually add inline keyword in front of the definitions

Using templates just to "work-around" this error is not a good idea. Use templates only when you need them.

like image 33
Kiril Kirov Avatar answered Oct 28 '25 12:10

Kiril Kirov