I am trying to write a file with extension h and a cpp file. When i try to compile the cpp file it gives me an error that says. [Linker error] undefined reference to `counter::counter()' . Could anyone help me out please. I am using a Dev.c++ compiler

Here are the classes below.

// File: counter.h

#ifndef COUNTER_H
#define COUNTER_H

class counter
{
public:
counter();
counter(int);

void increment();

void decrement();

void setcount(int);

void setmaxv(int);

int getcount() const;

int getmaxv() const;

private:

int count;
int maxv;
};
#endif // COUNTER_H

THIS IS THE CPP FILE

#include "counter.h"
#include <iostream>
using namespace std;

int main()
{
counter c1;

counter c2(10);

c1.setcount(50);
c1.decrement();
c1.decrement();
c1.increment();
cout << "Finav c1" << " " << c1.getcount() << endl;

c2.increment();
c2.increment();
c2.decrement();
cout << "Final c2 " << c2.getcount() << endl;

return 0;
}

The cpp file used to define the methods in the h file shouldn't have main() in it. The driver program, which is also a cpp file, will have main in it. It would have been nice if the driver files were given a different extension than the files used to define class methods but they are what they are. Don't give the driver program and the header file the same name.

a.h
a.cpp //where methods in a.h are defined. May be blank if all methods inlined.
b.cpp //driver program where a.h is included and a.cpp linked by association with a.h

[Torbecire]

O.k lets see if i get this right.

a.h is the class file
a.cpp is the implementation file for a.h
b.cpp is the uses both of the above to carry out its task

Yup. You include a.h in b.cpp and you're ready to go.

[Torbecire]

It worked thanks man.

You're welcome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.