Cannot create a method in a class - c++

I am new to c++ but have had some experience with java. I am trying to create a class but when i attempt to make a new method in the class I get several error (this is my .cpp file)
//.cpp file
#include "Test.h"
#include "Test.h"
#include <iostream>//unresolved inclusion
using namespace std;
void speak() {
if (happy) {//Symbol hapy could not be resolved
cout << "Meouw!" << endl;
} else {
cout << "Ssssss!" << endl;
}
}
void Test::makeHappy() { // member decleration not found
happy = true;//Symbol hapy could not be resolved
}
void Test::makeSad() { // member decleration not found
happy = false;//Symbol hapy could not be resolved
}
I dont get any errors in my heder file but have included it just in case
#ifndef TEST_H_
#define TEST_H_
class Test {
private:
bool happy;
public:
void makeHappy();
void makeSad();
void speak();
};
#endif /* TEST_H_ */
Finally I have another .cpp file I use which also gets errors
#include <iostream>//unresolved inclusion
#include "Test.h"
#include "Test.cpp"
using namespace std;
int main() {
Test jim;
jim.makeHappy();//method make happy could not be resolved
jim.speak();//method speak could not be resolved
Test bob;
bob.makeSad();//method make happy could not be resolved
bob.speak();//method speak could not be resolved
return 0;
}
This is the new error message I get when compiling
<!-- begin snippet: js hide: false -->
Sorry if this question is to open ended but I just cannot seem to find answers elsewhere.

this is your header file Test.h:
happy member was named bhappy_
for a private member think to add a getter and setter public member functions
#ifndef TEST_H_
#define TEST_H_
class Test {
private:
bool bhappy_;
public:
Test() // ctor
virtual ~Test() // dtor
public:
void makeHappy();
void makeSad();
void speak();
};
#endif /* TEST_H_ */
this is your Test.cpp file:
It's not advised to use using namespace std;
Don't include your header two times
//.cpp file
#include "Test.h"
#include <iostream>//unresolved inclusion
//ctor
Test::Test() : bhappy_(false)
{}
Test::~Test(){}
void Test::speak() {
if (bhappy_) {//Symbol hapy could not be resolved
std::cout << "Meouw!" << endl;
} else {
std::cout << "Ssssss!" << endl;
}
}
void Test::makeHappy() {
bhappy_ = true;//Symbol hapy could not be resolved
}
void Test::makeSad() { // member decleration not found
bhappy_ = false;//Symbol hapy could not be resolved
}
This is your main function:
#include "Test.h"
int main(int argc, char** argv) {
Test jim;
jim.makeHappy();//method make happy could not be resolved
jim.speak();//method speak could not be resolved
Test bob;
bob.makeSad();//method make happy could not be resolved
bob.speak();//method speak could not be resolved
return 0;
}

You need specify Test::speak().
Take should use this. to use class attribut. Think about getter and setter.
And finally, look C++ training, it should be usefull ^^ .
See you.

Related

In function int main(): class name was not declared in this scope

Im using vscode and im new to c++. I learned how to create a header file link to its cpp and use it to main.cpp. The only problem bugs me out is why it causes an error this is my simple code.
Name.h
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
Name.cpp
#include "Name.h"
void myname::setname(std::string name)
{
Name = name;
}
void myname::prname()
{
std::cout<<"Hello :"<<Name<<std::endl;
}
Maiin.cpp
#include <iostream>
#include <string>
#include "Name.h"
using std::cout;
using std::string;
using std::endl;
int main()
{
myname Epoy; // IN FUNCTION INT MAIN: ERROR myname was not declared in this scope
Epoy.setname("Jomar"); //note myname <-rename "BUT THIS IS NOT THE ERROR CAUSE THIS JUST HAPPEN BECAUSE OF THE ERROR ABOVE "
Epoy.prname();
return 0;
}
also i tried so many method i even compiled this by using g++ Maiin.cpp Name.cpp - o Maiin
Still didnt work
Edit: Community want me to add more details.
What I asked was, have you write header guards in your header file: #ifndef Name_H, #define Name_H, #endif ? Since you use vscode you have to done it manually.
Like this:
#ifndef Name_H
#define Name_H
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
#endif
you missing a C++ constructor:
class Foo {
public:
Foo() { /* your init code */ } // <-- this is a std. C++ constructor
~Foo() { /* your clean-up code */ } // <-- this is a std. C++ de-structor
};
int main(int argc, char **argv) {
Foo bar; // here, you don't need the: ( ) object on heap !
}

linking static class member function throws undefined reference error c++

I've gone through many similar threads on this kind of question but I'm still unable to resolve this error. Any help would be appreciated.
/*samp.h header file*/
#include<iostream>
using namespace std;
class test
{
private:
test();
public:
static void const_caller();
};
/*samp.cpp file*/
#include<iostream>
using namespace std;
class test
{
private:
test()
{
cout<<"priv cont called\n";
}
public:
static void const_caller()
{
cout<<"calling priv const\n";
}
};
/*main.cpp file */
#include"samp.h"
using namespace std;
int main(int argc, char **argv)
{
test::const_caller();
}
when I do
g++ samp.cpp main.cpp -o main.out
I get this error
/usr/bin/ld: /tmp/ccHZVIBK.o: in function `main':
main.cpp:(.text+0x14): undefined reference to `test::const_caller()'
which I'm unable to resolve since quite some time now.
In the samp.cpp file you define test class again.
You need to include samp.h header and implement methods of test class:
#include "samp.h"
using namespace std;
test::test()
{
cout << "priv cont called\n";
}
void test::const_caller()
{
cout << "calling priv const\n";
}
With your posted code, the .cpp file contains its own definition of the class that has the same name as the class in the .h file but it is really a different class.
In the .cpp file, you need to use:
test::test()
{
cout<<"priv cont called\n";
}
void test::const_caller()
{
cout<<"calling priv const\n";
}

Ttrying to understand Classes and headers

**PROBLEM SOLVED. It appears that i had created an extra header by mistake, and since i deleted him , it worked. **
So i am trying to understand about classes and headers and how i can make them work together.
I am following an online tutorial but it seems that something is going wrong in my code.
The problem is that when i try to run the main it gives me this error:
multiple definition of Cat::speak() and all the other functions.
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
int main()
{
Cat jim;
jim.makehappy();
jim.speak();
Cat george;
george.makesad();
george.speak();
return 0;
}
class.cpp
#include <iostream>
#include "class.h"
using namespace std;
void Cat::speak()
{
if (happy)
{
cout << "meoww" << endl;
}
else
{
cout << "sssss" << endl;
}
}
void Cat::makehappy()
{
happy = true;
}
void Cat::makesad()
{
happy = false;
}
class.h
#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED
class Cat
{
private:
bool happy;
public:
void makehappy();
void makesad();
void speak();
};
#endif // CLASS_H_INCLUDED
From what you have shown here there should be no problems. What you could do to temporarily resolve this to find out if you are actually defining this function in several places is to wrap your class in a namespace.
class.h
#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED
namespace myNamespace {
class Cat {
private:
bool happy;
public:
void makehappy();
void makesad();
void speak();
};
} // namespace myNamespace
#endif // CLASS_H_INCLUDED
class.pp
#include <iostream>
#include "class.h"
// using namespace std; // Don't Use - This is Bad Practice
// Can cause name clashing when trying to resolve name lookup
namespace myNamespace {
void Cat::speak() {
if (happy) {
std::cout << "meoww" << std::endl;
} else {
std::cout << "sssss" << std::endl;
}
}
void Cat::makehappy() {
happy = true;
}
void Cat::makesad() {
happy = false;
}
} // namespace myNamespace
main.cpp
#include <iostream>
#include "class.h"
// using namespace std; // Again -Bad Practice
int main() {
using namespace myNamespace;
Cat jim;
jim.makehappy();
jim.speak();
Cat george;
george.makesad();
george.speak();
return 0;
}
Try this to see if you are getting the same compiler error. This should help you to see if you are defining this function in multiple spaces. Also by removing the using namespace std; and just using the scope resolution operator to the std:: namespace will help to eliminate any possible problems and any possible future problems.
How are you compiling the code? You need to make sure that you are building the specific "class.o" and "main.o" files separately before linking them together. Here is an example Makefile.
all: main
main: main.o class.o
g++ main.o class.o -o main
main.o: main.cpp class.h
g++ -c main.cpp
class.o: class.cpp class.h
g++ -c class.cpp
It looks like you are using double inclusion guards so I don't think that is the problem. Check out this answer for a more in-depth explanation of what is happening: Error with multiple definitions of function

How to correctly extend a class in C++ and writing its header file?

I've got a third party library named person.lib and its header person.h. This is my actual project structure and it compiles and runs perfectly.
Actual Structure:
main.cpp
#include <iostream>
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
using namespace person;
using namespace std;
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
I want to refactor my code by dividing the declaration of my Client class from its definition and create client.h and client.cpp. PAY ATTENTION: sayHello() and onMessage(const * char const) are functions of the person library.
Refactored Structure:
main.cpp
#include <iostream>
#include "client.h"
using namespace person;
using namespace std;
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
client.cpp
#include "client.h"
using namespace person;
using namespace std;
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
client.h
#ifndef CLIENT_H
#define CLIENT_H
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
#endif
As you can see, I've simply created a client.h in which there's the inclusion of the base class person.h, then I've created client.cpp in which there's the inclusion of client.h and the definitions of its functions. Now, the compilation gives me these errors:
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2440: 'inizialization': unable to convert from 'Client *' to 'person::impl::Person *' main.cpp 15 1 Test
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2039: 'setName': is not a member of 'Client' client.cpp 8 1 Test
error C3861: 'sendMessage': identifier not found client.cpp 34 1 Test
It's a merely cut&copy refactoring but it doesn't work and I really don't understand WHY! What's the solution and why it gives me these errors? Is there something about C++ structure that I'm missing?
Here's a dog-n-bird implementation (ruff ruff, cheep cheep)
cLawyer is defined and implemented in main.cpp, while cPerson and cClient are defined in their own header files, implemented in their own cpp file.
A better approach would store the name of the class. Then, one wouldn't need to overload the speak method - one could simply set the className in each derived copy. But that would have provided in my estimates, a less useful example for you.
main.cpp
#include <cstdio>
#include "cClient.h"
class cLawyer : public cPerson
{
public:
cLawyer() : cPerson() {}
~cLawyer() {}
void talk(char *sayWhat){printf("cLawyer says: '%s'\n", sayWhat);}
};
int main()
{
cPerson newPerson;
cClient newClient;
cLawyer newLawyer;
newPerson.talk("Hello world!");
newClient.talk("Hello world!");
newLawyer.talk("Hello $$$");
return 0;
}
cPerson.h
#ifndef cPerson_h_
#define cPerson_h_
class cPerson
{
public:
cPerson();
virtual ~cPerson();
virtual void talk(char *sayWhat);
protected:
private:
};
#endif // cPerson_h_
cPerson.cpp
#include "cPerson.h"
#include <cstdio>
cPerson::cPerson()
{
//ctor
}
cPerson::~cPerson()
{
//dtor
}
void cPerson::talk(char *sayWhat)
{
printf("cPerson says: '%s'\n",sayWhat);
}
cClient.h
#ifndef cClient_h_
#define cClient_h_
#include "cPerson.h"
class cClient : public cPerson
{
public:
cClient();
virtual ~cClient();
void talk(char *sayWhat);
protected:
private:
};
#endif // cClient_h_
cClient.cpp
#include "cClient.h"
#include <cstdio>
cClient::cClient()
{
//ctor
}
cClient::~cClient()
{
//dtor
}
Output
cPerson says: 'Hello world!'
cClient says: 'Hello world!'
cLawyer says: 'Hello $$$'
Suggestions noted above:
//In the cPerson class, a var
char *m_className;
//In the cPerson::cPerson constructer, set the var
m_className = "cPerson";
//Re-jig the cPerson::speak method
void cPerson::speak(char *sayWhat)
{
printf("%s says: '%s'\n", m_className, sayWhat);
}
// EDIT: *** remove the speak methods from the cClient and cLawyer classes ***
//Initialize the clas name apporpriately in derived classes
//cClient::cClient
m_className = "cClient";
//Initialize the clas name apporpriately in derived classes
//cLaywer::cLaywer
m_className = "cLawyer";
You are declaring the class Client twice - once in the .h file and once in .cpp. You only need to declare it in the .h file.
You also need to put the using namespace person; to the .h file.
If class Person is in namcespace person, use the person::Person to access it.
The client.cpp must contain definitions only!
I think for the linker the class Client defined in client.h and class Client defined in client.cpp are different classes, thus it cannot find the implementation of Client::Client(). I purpose to remove the declaration of class Client from the client.cpp and leave there only definitions of functions:
// client.cpp
#include <time.h>
#include <ctype.h>
#include <string>
#include "client.h"
using namespace std;
Client::Client()
{
//DO STUFF
}
void Client::onMessage(const char * const message)
{
//DO STUFF
}
void Client::gen_random(char *s, const int len) {
//DO STUFF
}

'Undefined reference to Class::method()'

Recently I've been learning how to create methods within classes so that I only have to write a method once and for each of that class I instantiate I can call the one method and it will work only on the variables of the object that called it, I know how to do this when only using main.cpp and no headers however I am confused on how I should be writing this when I use a class header and cpp.
I have a sample of code similar to what I want to achieve:
#include <iostream>
using namespace::std;
class Object
{
public:
int stuff;
void manageStuff();
Object();
};
void Object::manageStuff()
{
stuff++;
}
Object::Object() : stuff(0) {}
Object object1, object2;
int main() {
for (int i = 0; i < 10; i++)
{
object1.manageStuff();
object2.manageStuff();
cout << object1.stuff << "\n";
cout << object2.stuff << "\n";
}
}
This works fine and allows me to have two instances of Object and a method that works independently for each instance, this is my current project:
main.cpp:
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test test;
for (int i = 0; i < 10; i++)
{
test.count(); // Here's my error "undefined reference to Test::count"
}
return 0;
}
Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;
Test::Test()
{
//ctor
}
Test::~Test()
{
//dtor
}
Test.h
#include <iostream>
#ifndef TEST_H
#define TEST_H
class Test
{
public:
Test();
virtual ~Test();
void count();
int counter();
};
#endif // TEST_H
and finally TestFunctions.h
#include <iostream>
#include "Test.h"
#ifndef TESTFUNCTIONS_H_INCLUDED
#define TESTFUNCTIONS_H_INCLUDED
void Test::count()
{
Test::counter++;
std::cout << Test::counter;
}
#endif // TESTFUNCTIONS_H_INCLUDED
I'm sure that there will be something that's very obviously wrong to a more seasoned programmer and I'm about to look a bit thick but any help would be greatly appreciated
Thanks!
I would suggest getting rid of TestFunctions.h, and adding the implementation of Test::count() to Test.cpp. Currently, the TestFunctions.h header is not included anywhere, so you have no access to the definition from main.
You defined (i.e. implemented) Test::count() in a header file (TestFunctions.h), but you never included it anywhere so the code there is not compiled.
You should change it to be in a .cpp file, compile it and link it with the other source files. There's no reason why not to place it in Test.cpp.
Rename TestFunctions.h into TestFunctions.cpp, make it compiled same way as main.cpp and linked.
Alternatively, include TestFunctions.h somewhere, e.g. main.cpp