I'm currently getting started in C++. For the homework I'm currently doing, I have to define a number of classes in one header file. I'm not sure If I'm doing this right. Here is sample of what I'm trying to do.
//classOne.h
class classOne{
public:
classOne();
~classOne();
class classInsideClass{
public:
classInsideClass
void hello();
void print();
};
}
(I have skipped some code in this sample, like constructor for classOne)
//classOne.cpp
classOne::classInsideClass::classInsideClass(){}
classOne::classInsideClass::hello(){
cout << ""Hello <<endl;
}
//main.cpp
classOne callingClass;
callingClass.classInsideClass.hello;
I have defined a class inside classOne's header file. And I have created the functions for the this classInsideClass, inside the classOne's cpp. Is this the right way of saying, classInsideClass belongs to classOne, or am I not allowed to do this?
Am I calling the functions of classInsideClass correctly in main.cpp? When I try to run this, I get following error;
error:invalid use of 'class classOne::classInsideClass
If I don't try and call a function of classInsideClass in main.cpp, it complies fine.
Thanks in advance.
classInsideClass is a type inside of classOne, not an object. If you want to call classInsideClass::hello(), you need an actual instance of classInsideClass:
classOne::classInsideClass callingClass;
callingClass.hello();
//classOne.h
...
class classInsideClass{
public:
classInsideClass();
void hello();
};
Here you've missed the parentehsis at the end of the constructor definition.
void classOne::classInsideClass::hello(){
cout << "Hello" <<endl;
}
Here the function return type is missing and the quote marks are supposed to be around the string.
Good luck!
Try:
//main.cpp
classOne::classInsideClass internalClassObject;
internalClassObject.hello();
Related
So i just learned how to seperate classes and the youtube totourial is stressing on doing this alot, here's the link
https://www.youtube.com/watch?v=NTip15BHVZc&list=PLAE85DE8440AA6B83&index=15
My code is the exact same as his, and in the cpp file theres this thing:
mainClass::myfunction; (mainclass is the name of my class, myfunction is my function)
when i try to execute my program, it gives an error:
unidentified reference to 'mainClass::myfunction()'
here's my main.cpp file code:
#include <iostream>
#include "mainclass.h"
using namespace std;
int main()
{
mainClass bo;
bo.myfunction();
return 0;
}
here's my mainclass.h code:
#ifndef MAINCLASS_H
#define MAINCLASS_H
class mainClass
{
public:
myfunction();
};
#endif // MAINCLASS_H
my mainclass.cpp:
#include "mainclass.h"
#include <iostream>
using namespace std;
mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
I don't know much about these so could you just tell me what the errors here are, because i copied everything correctly from the guy's totourial but still it doesn't work
P.S: this happens to me alot, i understand everything, nothing works, i copy everything, nothing works, and then i literally do exactly what the person is doing, still nothing works on all three of PC's, so i dont think the problem is with the devices lol
I doubt you completely copied and pasted that code because I'm fairly sure a teacher shouldn't be teaching having functions without a specified return type, but let's jump into it anyways...
Possibility #1
You meant to create a constructor for the class. In that case, please make sure the constructor function has the same name as the class. Also, you can't call it through .mainClass(), as it is a constructor.
class mainClass
{
public:
mainClass();
};
mainClass::mainClass()
{
cout << "I am a banana" << endl;
}
Possibility #2 You meant to create the class member function myfunction. You really should be specifying what return type your function is of. Some compilers will auto-assume int return type, and so the function you created is int myfunction();, but you really should be specifying it as void myfunction(); since you didn't return anything. Addl. info: Does C++ allow default return types for functions?
Next, change how you are giving the definition, by adding the return type.
void mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
Possibility #3 Those should work, but another issue is that you might not have linked mainclass.cpp, so there is no definition available. In code blocks, right click on the project name and hit Add Files, then add the mainclass.cpp so the linker can define mainClass::myfunction().
To troubleshoot if the mainclass.cpp is being built with the project, try adding
#error I'm included! to the file mainclass.cpp after #include "mainclass.h". If you get an error I'm included!, then it is linked and you can remove the #error.
So I am working on my first multiple file, non-toy, c++ project. I have a class that represents a multi-spectral image and all the information that goes along with it.
My problem is how to design the part of the program that loads and object of this class with a file from disk!
I don't think I need a class for this. Would switching to a functional approach be better for the file loading. This way I can have just a source file (.cpp) that has functions I can call while passing in pointers to the relevant objects that will be updated by the file accessed by the function.
I don't think static functions are what I want to use? As I understand it they(static functions) are for accessing static variables within a class, aren't they?
If I go the functional route, from main(), how do I access these functions? I assume I would include the functions .cpp file at the beginning of the main() containing file. From there how do I call the functions. Do i just use the function name or do I have to pre-pend something similar to what you have to pre-pend when including a class and then calling its methods.
Here is some example code of what I have tried and the errors I get.
OpenMultiSpec.cpp
#include <iostream>
void test(){
std::cout << "Test function accessed successfully" << std::endl;
}
main.cpp
int main(){
test();
return 1;
}
The error says " 'test' was not declared in this scope "
OpenMultiSpec.h
void test();
main.cpp
#include "OpenMultiSpec.h"
int main(){
test();
return 1;
}
If they're in two separate files, and in your case, one being a header, use
#include "OpenMultiSpec.h"
If you decide to only use one file (as your comment says above), you won't need #include for your header file. Just place your function declaration anywhere before you call it.
#include <iostream>
void test() {
std::cout << "Test function accessed successfully" << std::endl;
}
int main() {
test();
return 1;
}
i have two questions that are fairly small and related so i will put them both in the same question.
i have been experimenting with classes and i was attempting to access a class in another file that wasn't in a class so for example.
//class 1 .cpp
void Class1::function1()//another error
{
function()
}
//main.cpp
void function()
{
//stuff happens
}
is there a way to-do this? or would i need to add this function to a class to get it to work. also how would you go about creating a function that receives a function as it parimetre? for example function(function2())
i am simply trying to access a function from a class as it would make my code easier to use later if the function that i am using doesn't get added to a class. with regards to the seconds question i which to create a function that receives a time and a function as an argument. it will wait for the specified time then execute the program
How to access a function in another file?
Depends on the type of function, there can be to cases:
1. Accessing class member functions in another file(Translation Unit):
Obviously, you need to include the header file, which has the class declaration in your caller translation unit.
Example code:
//MyClass.h
class MyClass
{
//Note that access specifier
public:
void doSomething()
{
//Do something meaningful here
}
};
#include"MyClass.h" //Include the header here
//Your another cpp file
int main()
{
MyClass obj;
obj.doSomething();
return 0;
}
2. Accessing free functions in another file(Translation Unit):
You do not need to include the function in any class, just include the header file which declares the function and then use it in your translation unit.
Example Code:
//YourInclude.h
inline void doSomething() //See why inline in #Ben Voight's comments
{
//Something that is interesting hopefully
}
//Your another file
#include"YourInclude.h"
int main()
{
doSomething()
return 0;
}
Another case as pointed out by #Ben in comments can be:
A declaration in the header file, followed by a definition in just one translation unit
Example Code:
//Yourinclude File
void doSomething(); //declares the function
//Your another file
include"Yourinclude"
void doSomething() //Defines the function
{
//Something interesting
}
int main()
{
doSomething();
return 0;
}
Alternately, a messy way to do this can be to just mark the function as extern in your another file and use the function.Not recommended but a possibility so here is how:
Example Code:
extern void doSomething();
int main()
{
doSomething();
return 0;
}
How would you go about creating a function that receives a function as it parameter?
By using function pointers
In a nutshell Function pointers are nothing but pointers but ones which hold address of functions.
Example Code:
int someFunction(int i)
{
//some functionality
}
int (*myfunc)(int) = &someFunction;
void doSomething(myfunc *ptr)
{
(*ptr)(10); //Calls the pointed function
}
You need a prototype for the function you want to call. A class body contains prototypes for all its member functions, but standalone functions can also have prototypes. Typically you organize these in a header file, included from both the file which contains the function implementation (so the compiler can check the signature) and in any files which wish to call the function.
(1) How can the `class` function be accessible ?
You need to declare the class body in a header file and #include that wherever needed. For example,
//class.h
class Class1 {
public: void function1 (); // define this function in class.cpp
};
Now #include this into main.cpp
#include"class.h"
You can use function1 inside main.cpp.
(2) How to pass a function of class as parameter to another function ?
You can use pointer to class member functions.
I have a cyclical redundancy circular dependency between two classes in my project, StatusEffect and BaseCharacter.
Both classes need to be aware of each other as the BaseCharacter needs to store a set of StatusEffects and StatusEffect needs to be able to do operations on BaseCharacter. I don't think it's possible to eliminate this behavior and still have it work correctly. Here's what I'm trying to do right now:
Base Character exists inside the namespace Game::Character and StatusEffect exists inside the namespace Game::StatusEffects
inside StatusEffects.h, I forward declared BaseCharacter like so:
namespace Game {
namespace Character {
class BaseCharacter;
}
}
then below it I have:
namespace Game
{
namespace StatusEffects
{
class StatusEffect
{
public:
virtual void TickCharacter(Game::Character::BaseCharacter* character, int ticks = 1)
{
std::cout << "Name " << character->GetName() << std::endl;
}
protected:
private:
std::string name;
int StatusEffectUID;
};
}
}
However, this is giving me a compiler error:
Error 1 error C2027: use of undefined type 'Game::Character::BaseCharacter'
I thought that because I'm using a pointer, this forward declaration is fine. Is there something else I need to forward declare? I dont need to forward declare the whole class definition do I?
You can't call a method through a pointer to a forward-declared class. You have to move this code somewhere where the class is already defined - for example into a .cpp file that includes both classes definition.
Your forward declaration is fine. However, you must not refer to any of the members of such a class.
You should only declare the TickCharacter method in the header. You should then define the StatusEffect::TickCharacter method in its own module file after #include ing the header file which contains the full declaration of BaseCharacter.
I need to call properties and functions of an object from a different class.
The idea is passing 'this' as a parameter to the other class constructor. E.g.:
instance = ClassName(this);
And then do:
ParentClass parentInstance;
ClassName::ClassName(MainApp _instance){
parentInstance = _instance;
}
However, my compiler says that ParentClass does not name a type. Ideas?
Also, should I use a pointer to save memory? How?
Thanks in advance.
UPDATE:
Ok, sorry for the delay. Here it goes the actual code. First, a simple class.
Game class:
Header file
#ifndef _GAME
#define _GAME
#include "ofMain.h"
class Game{
public:
Game();
~Game();
void hi();
};
#endif
cpp file:
#include "Game.h"
Game::Game(){}
Game::~Game(){}
void Game::hi(){
cout << "hi, I'm game! " << endl;
}
Then, from MainApp I create the object:
- Relevant code on header file:
#ifndef _MAIN_APP
#define _MAIN_APP
#include "ofMain.h"
#include "Game.h"
class MainApp : public ofSimpleApp{
public:
Game game;
};
#endif
Relevant code on the cpp file:
game = Game();
game.hi();
This obviously works as I'm only creating a bloody object. However, problem comes with composition.
I could pass the main app as argument in the constructor, I could pass it via game.setParent(this);... problem is, I can't even define the variable to store the reference to the app.
E.g.: (making it easy/inefficient without pointers or anything)
Game.h:
#define _GAME
#ifndef _GAME
#include "ofMain.h"
#include "MainApp.h"
class Game{
MainApp app;
public:
Game();
~Game();
void hi();
};
#endif
This returns a "does not name a type" error and declaring class MainApp returns an "incomplete type" error
I'm sure I'm doing something dumb.
UPDATE 2:
The problem with that method is that I can't call a function of the pointed object now.
This is Game.h:
#ifndef _GAME
#define _GAME
#include "ofMain.h"
class MainApp;
class Game{
public:
Game();
Game(MainApp* _app);
~Game();
void hi();
MainApp* app;
};
#endif
As you see, app (of the type MainApp) is passed as a parameter. That's fine, MainApp exists as it's the forward declaration. However, when I try to call any of app's functions I can't (compiler error saying Request for member appHi in .... which is non-class type 'MainApp'.
MainApp is NOT included in Game.h but Game.h IS included in MainApp.h.
Ideas?
The problem is you have a circular reference - Game includes MainApp, and MainApp includes game. You need a 'forward declaration', as per the example by DeadMG.
See here.
It's called composition and is a common pattern. It's highly efficient in both semantics and in terms of runtime speed/memory footprint.
Your code example is a little too much pseudocode for me to read it correctly. Let me show you how it's done.
class X;
class Y {
...
void DoSomething(X* x, ... args);
};
class X {
Y y;
void DoSomething() {
y.DoSomething(this, args);
}
};
I think there may be two issues here:
1) You need to declare the ParentClass (i.g. #include its .hpp-file) before using it
2) The assignment "parentInstance = _instance" will invoke the assignment operator, which i'm guessing is not what you want. let "parentInstance" be a pointer instead.
Note the section on "#include."
http://www.cplusplus.com/doc/tutorial/program_structure/
After the "Intro to the C++ Language" section look for the verbiage about #include.
http://www.cprogramming.com/tutorial/lesson1.html
Namespaces:
http://www.tenouk.com/Module23.html
HTH
That's not how things work in C++. Unlike javascript, you cannot inject methods or fields into existing objects at runtime.
Madsen is on the right track here, but we need more code; What is the class heirarchy of ParentClass, ClassName and SaleraApp. Which classes are base and/or dervied?
When you write: parentInstance = _instance; the compiler will try to generate a default copy constructor if one is not defined. Your problem might be that you are trying to create a dervied class object from a base class pointer.
Also, "this" is a pointer.
If all you need to do is use functions and data members of another class, read up on the friend keyword. It will allow access to class members from other classes.
UPDATE: Alternatively, store a pointer or reference to the object you need access to, and make getters for data members and make the functions public... but I get the feeling this is not what you're after...