Member function definition outside the class - c++

Firstly, I am giving the codes. Then I am explaining the problem I am facing.
main.cpp
#include <iostream>
#include "acc.h"
using namespace std;
class mem;
int main()
{
show();
return 0;
}
acc.h
#ifndef ACC_H
#define ACC_H
#include "acc.cpp"
void show();
class mem{
int a;
public:
void showa();
void seta(int A);
};
#endif
acc.cpp
#include <iostream>
using namespace std;
void mem::showa(){cout<<a<<endl;}
void mem::seta(int A){a = A;}
void show()
{
mem m;
m.seta(22);
string ss;
cin>>ss;
cout<<"MY name is "<<ss<<" ";
m.showa();
}
"mem" class I declared in "acc.h" file already and added that "acc.h" into acc.cpp file also. But when I am calling that class from a function. It can't response. Showing "a" and "mem" not declared. How can I perfectly link that class definition and member functions of that class so that calling member functions of that class from another function can't create any problem?

If you remove the #include "acc.cpp" from the acc.h file it should compile without any errors. I tried and it compiles for me. I am using Visual Studio 2010 for the same.
Other than this, few more comments:
You can use #pragma once in you header file instead of #ifndef/#define macros. The former is more cleaner.
You dont need to forward declare class mem before main() as you are already including acc.h.
the show() can be moved to where main() is defined making the acc.h/acc.cppfiles dedicated for the mem class.
A header file should always be named after the class it is holding i.e. mem.h/mem.cpp in your case. This informs which file contains which class even without opening the file.

Related

trouble with accessing a class from a different class

just started to learn c++.I'm trying new things in c++ on thing i wanted to try is to access a class from another class and change its instances and print its instance on screen.
I would like to know 2 things 1)whats wrong with my code 2)where should i declare class declarations (in main file or class definition file?)
here is the error log -
'object::carrier' uses undefined class 'sub'
'cout': is not a member of 'std'
'cout': undeclared identifier
this is what i came up with-
source.h
#include <iostream>
#include <vector>
#include "stuff.h"
int main()
{
object spoon(3);
spoon.get();
}
stuff.cpp
#pragma once
#include <vector>
class object;
class sub;
class object
{
private:
std::vector <sub> thing;
public:
object(int n);
void get() const;
};
class sub
{
private:
int num;
public:
void set_num(int n);
};
stuff.cpp
#include <vector>
#include "stuff.h"
// methods for object
object::object(int n)
{
sub carrier;
carrier.set_num(n);
}
void object::get() const
{
std::cout << carrier.num;
}
// methods for sub
void sub::set_num(int temp_num)
{
num = temp_num;
}
thanks
In your object class, specifically object::get definitions, you use the variable carrier without it being in scope.
When you declare the variable sub carrier in your constructor, it is only accessible in the same scope, that is, inside the constructor. Once your program leaves the scope, the variable carrier is deallocated (deleted).
You must add the variable sub carrier as a member to your class like so:
class object
{
private:
sub carrier
// other stuff
}
Edit:
I so you edited your question.
You must either replace cout with std::cout because cout is part of the c++ standard library. Alternatively, a less verbose option would be to add using namespace std; at the top of every .cpp file. This basically tells the compiler that you can use the namespace std without explicitly saying it. But don't do it for .h files. It's not a good idea.

C++ - 'class' type redefinition

I made a smaller reproducible version of the code that gave me these errosr: 'MyNamespace::MySecondClass': 'class' type redefinition, 'print': is not a member of 'MyNamespace::MySecondClass'. Is there any way of working around this problem?
// MyClass.h
#pragma once
namespace MyNamespace {
class MySecondClass {};
}
// MyClass.cpp
#include "MyClass.h"
#include <iostream>
using namespace std;
class MyNamespace::MySecondClass
{
public:
void print(const char* msg)
{
cout << msg << endl;
}
};
The problem is that in MyClass.h you define a class MySecondClass as an empty class. When you the define your class in MyClass.cpp you give a different definition, which contains some new members. This infringes the One Definition Rule (ODR).
Solution 1
remove {} in the header. This will tell the compiler that you declare that such a class exists but that it will be defined later. Your code would compile. Unfortunately if you’d include the header in other cpp, these could make only a very very limited use of MySecondClass.
Solution 2
define in the header the class with all its members (but without providing the implementation of the member functions:the signature is sufficient). This would allow the class to be used in whichever cpp that
would include it:
// MyClass.h
#pragma once
namespace MyNamespace {
class MySecondClass {
public:
void print(const char* msg);
};
}
You’d then define the members of the class in its cpp in the appropriate namespace:
// MyClass.cpp
#include <iostream>
#include "MyClass.h"
using namespace std;
namespace MyNamespace {
// member functions
void MySecondClass::print(const char* msg)
{
cout << msg << endl;
}
}
Remark: the include sequence in the cpp should first include the standard library headers, then only your own headers. It makes no difference in your simple example, but better get used the good practices immediately.

Can't find find out why it doesn't compile [duplicate]

I have a very simple program that doesn't compile due to multiple definition error. It is here:
main.cpp
#include <iostream>
#include "read_p.h"
using namespace std;
int main()
{
return 0;
}
read_p.cpp
#include "read_p.h"
using namespace std;
void read_p()
{
/*
some code here
*/
}
read_p.h
#ifndef READ_P_H
#define READ_P_H
#include "buildings.h"
void read_p();
#endif
buildings.h
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include "flag.h"
using namespace std;
/*
some class here
*/
#endif
flag.h
#ifndef FLAG_H
#define FLAG_H
using namespace std;
class
Test
{
private:
public:
int test_var;
Test(int);
};
Test::Test(int a)
{
test_var = a;
}
#endif
The compiler gives me the error that the constructor Test::Test is defined multiple times. Unlike questions I find online, this error is not due to including the cpp-file instead of the h-file.
Question: Where does the multiple definition of the constructor occur? And is the proper way to circumvent the issue by making the constructur inline?
Change
Test(int);
to
inline Test(int);
Even better, fix your class definition to define member functions inline, which makes them implicitly inline:
class Test
{
public:
int test_var;
Test(int a) : test_var(a) {}
};
Otherwise, as always, defining a function in a header means that it gets defined in every translation unit that includes that header, which leads to multiple definitions.

Unreferenced function inside a namespace

I am new at C++ language and I am trying to understand why the next thing is happening:
I have a header file header.h
namespace myNamespace{
class myClass{
public:
myClass();
~myClass();
void myFunction(void);
}
void myVoid();
}
The definitions are in header.cpp
using namespace myNamespace;
void myClass::myFunction(void){
//DO anything
}
void myVoid(){
//Do anything
}
And in the main.cpp I have the follow:
#include "header.h"
main(){
myVoid();
myNamespace::myVoid();
}
Why If I try to call myFunction of the class myClass from the main I have a successful compile, and if I try to call the function as in the main file I have an undefined reference error? I can fix it if in the header.h moves myVoid out of the namespace.
Why is this happening? I am trying to figure out how this works.
Thanks in advice,
If you don't specify definition of myVoid (I mean just declaring it like you did), then the compiler can never be sure if you are implementing the function which is declared in namespace or just defining a new one.
On the other hand, if you are defining myClass::myFunction, it has to be the method that is declared in the defined class.
To make it clear, investigate the following code and take a look here (very similar question)
namespace Test {
int myVoid(void); // declaration
class yourClas; // declaration
class myClass{ // definition
public:
myClass();
~myClass();
void myFunction(void); // declaration which belongs to defined class
}
}
void myVoid() {
// definition, but compiler can't be sure this is the function
// that you mention in the namespace or a new function declaration.
}
void myClass::myFunction(void){
// absolutely definition for the method of the corresponding class
}

C++: Error with 'this' keyword

I am attempting to create an poptart vending machine program within c++ and i am trying to use the this keyword, however i am always getting an error stating 'this' may only be used inside a nonstatic member function. Below is a part of the code that i am getting one such issue in
Code:
#include <iostream>
#include "HasCredit.h"
using namespace std;
void insertMoney(int money)
{
cout<<"You inserted: " << money;
money = money+this->currentContext->getStateParam(Credit);
this->currentContext->setStateParam(Credit,money);
cout<< "Total: "<<money<<endl;
this->currentContext->setState(Has_Credit);
}
Any suggestions onto why i am getting this error will be most appreciated. Cheers.
Edit: the insertMoney method is within a class called HasCredit.
Edit2: member declarations are now made outside of the constructor
Edit3: Added state class declaration
The Class Definition Code is Below:
#include <iostream>
#include "State.h"
#include "StateContext.h"
using namespace std;
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) {
}
void insertMoney(int);
void MakeSelectionCoating(int);
void MakeSelectionFilling(int);
void moneyRejected(void);
void addPopTarts(int);
void dispense(void);
};
The state class declaration code is shown Below:
#include <iostream>
#include "Transition.h"
using namespace std;
class State: public Transition
{
protected:
StateContext* currentContext;
public:
State(StateContext* Context);
};
The this pointer is only valid inside a class. Your insertMoney function is not declared to be in a class. See http://www.learncpp.com/cpp-tutorial/87-the-hidden-this-pointer/.
In your definiton of insertMoney (in the code, not the class), you do not declare it to be a member of hasCredit. You need to use void hasCredit::insertMoney instead.
You probably want to attach insertMoney to a class. Try ClassName::insertMoney in your definition.
The error is telling you exactly why you're getting it.
The solution is to fix the definition of what you intend to be a member function, so that the compiler knows it is a member function. Like this:
// vv THIS WAS MISSING
void HasCredit::insertMoney(int money)
{
...
Your member declarations shown in the question are also in the wrong place. They need to be inside the class body, but outside the constructor. When overriding virtual member functions, you may want to show that to readers by using the virtual and override keywords. (Note, override only works if you have a new, C++11 compiler. For older compilers, use a comment /* override */ instead)
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) { }
// vv THIS....................CANNOT BE INSIDE HERE ^^
virtual void insertMoney(int) override;
...
};
You probably want some of your members to be public as well.
There are a few things wrong:
class definition:
#include <iostream>
#include "State.h"
#include "StateContext.h"
using namespace std;
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) {
}
void insertMoney(int);
void MakeSelectionCoating(int);
void MakeSelectionFilling(int);
void moneyRejected(void);
void addPopTarts(int);
void dispense(void);
};
Note that the methods should be declared outside of the constructor definition.
For the implemenation:
#include <iostream>
#include "HasCredit.h"
using namespace std;
void HasCredit::insertMoney(int money)
{
cout<<"You inserted: " << money;
money = money+this->currentContext->getStateParam(Credit);
this->currentContext->setStateParam(Credit,money);
cout<< "Total: "<<money<<endl;
this->currentContext->setState(Has_Credit);
}
The method must be qualified with the name of the class... otherwise it would be considered a definition of a function... and a function does not have a this