In main.cpp

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

Initialization Init;

int main() {
Init.test();

return 0;
}

In init.cpp

#include <iostream>
using namespace std;
class Initialization
{
public:

	void test()
	{
		for(int i=0; i<10; i++)
		{
			cout<<i;
		}
	}
};

In init.h

#ifndef INIT_H_
#define INIT_H_

class Initialization
{

public:
	void test();
};

#endif /* INIT_H_ */

Error is undefined reference to `Initialization::test()'

I can't figure out the problem. I just wanna test prototype a class and declare the class in main function.

Recommended Answers

All 4 Replies

You are attempting to re-declare the class in the implementation file (the *.cpp file) instead of simply implementing the member methods. What you need to do is declare it in the header (the *.h file), then implement it in the *.cpp file using the scope-resolution operator ( :: ):

//myClass.h
#ifndef MY_CLASS_H
#define MY_CLASS_H

class myClass {
 //...
 public:
   void sample();
   //...
};

#endif  //MY_CLASS_H
//myClass.cpp
#include "myClass.h"

void myClass::sample() {
  //...
}

Then, once declared and defined/implemented, you #include the header in main.cpp and add the *.cpp file to your project/make file.

In your init.cpp file you are re-declaring the class. You do not need to do this since you already prototyped it in init.h. In init.cpp it should be:

void Initialization::test()
{
   // Code for test() method here
}

Ooo Fbody beat me out by seconds haha :D

Thanks. It work.

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.