comp_sci5050
comp_sci5050

Reputation: 145

C++ How to Reference Other Classes?

I'm new to C++, and I'm having some trouble setting up a simple class reference.

Class: Test.hh

#ifndef _TEST_HH_
#define _TEST_HH_

class Test {
    public:
        Test (double x);
};

#endif

Class Test.cc

#include "Test.hh"
#include <stdio.h>

Test::Test(double x) {
   printf("%f",x);
}

Now I want to access this class from another class:

Class: DriverClass.hh

#ifndef _DRIVERCLASS_HH_
#define _DRIVERCLASS_HH_

#include "Test.hh"

class DriverClass {
    public:
        DriverClass(double y);
        Test *t;
}

#endif

Class DriverClass.cc

#include "DriverClass.hh"

DriverClass::DriverClass(double y) {
    t = new Test(y);
}

However, I get an error: "undefined reference to 'Test::Test(double)?

Does anyone know what might be wrong? Please assume that DriverClass is being called directly from a main method (not shown).

Upvotes: 2

Views: 2904

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

There is still an error in your post - a missing ; after the DriverClass declaration. The rest is correct.

You should compile and link all the sources. The following is a sample Makefile and a sample test code.

Makefile

all: t

t: t.cc DriverClass.cc Test.cc
    g++ -Wall -g -o $@ $^

clean:
    rm -f *.o t

However, note that it's generally recommended to compile the sources into objects separately in order to compile only the sources changed after the last compilation. For example:

CFLAGS=-Wall -g

all: t

t: t.o DriverClass.o Test.o
    g++ -o $@ $^

t.o: t.cc DriverClass.o Test.o
    g++ $(CFLAGS) -c $< -o $@

DriverClass.o: DriverClass.cc
    g++ $(CFLAGS) -c $< -o $@

Test.o: Test.cc
    g++ $(CFLAGS) -c $^ -o $@

clean:
    rm -f *.o t

I've used the GNU compiler. For the meaning of $@ and $^ variables refer to the official documentation.

t.cc

#include "Test.hh"
#include "DriverClass.hh"

int main(int argc, char const* argv[])
{
  DriverClass d(10.4);
  return 0;
}

Testing

$ make
g++ -Wall -g -o t t.cc DriverClass.cc Test.cc
$ ./t
10.400000

P.S.: don't forget to delete the allocated object.

Upvotes: 2

Related Questions