How to use c++ object defined in other file? - c++

I keep having problems with this. If I define an object in main.cc, how do I access that object from another .cc file?
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class object;
return 0;
}
file.cc:
#include "header.h"
void function()
{
object.method(parameter);
}
What would I have to put in header.h to get this working? Any help would be appreciated.

how do I access that object from another .cc file?
What would I have to put in header.h to get this working?
The simple answer to is to "pass the object by reference".
An object created in main() lasts for the entire program. This is typical in embedded systems ... I have no issues with this aspect.
I would, however, put the long lasting object in dynamic memory (because the stack is more limited).
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class* object = new Class;
function(*object); // <--- pass the object by reference
return 0;
}
file.cc:
#include "Class.h"
#include "header.h"
void function(Class& object) // <-- how to specify reference
{
object.method(parameter); // <-- you did not identify parameter
}
header.h
class Class; // <--- poor name choice
void function (Class& object); // <--- another poor name choice
// note that the compiler needs to know only that Class is a
// user defined type -- the compiler knows how big a reference
// or ptr to the class is, so you need not provide more Class info
// for this file
Of course, you still need to write Class.h and define Class
Update - You have marked this post as C++.
So, please consider the following (which sidesteps the pass by reference dilemma):
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class* object = new Class;
//
// I recommend you do not pass instance to function.
//
// Instead, the C++ way is to invoke an instance method:
object->function();
// and, if you've been paying attention, you know that the method
// Class::function()
// has access to the 'this' pointer of the class
// and thus the 'passing' of this instance information
// is already coded!
// some of your peers would say you must:
delete object;
// others would say this is already accomplished by the task exit.
return 0;
}

If you were to try something like...
file.cc:
#include main.cc
The compiler would be compiling main.cc twice -- which means it would see 2 definitions of everything in main.cc. This will cause you some problems.
It's better design (and actually compiles correctly! Bonus!) to create a custom header file for your classes, and then import this as necessary.
myclasses.h:
Class object;
file.cc:
#include myclasses.h

Related

Getting error: expected constructor, destructor, or type conversion before ‘(’ token

I am trying to make functions repository. I have created four files:
Function.hpp, Function.cpp, FunctionsRepository.hpp, FunctionsRepository.cpp
I want to keep pointers to functions in vector of pointers.
//FunctionsRepository.hpp
#ifndef FUNCTIONSREPOSITORY_HPP
#define FUNCTIONSREPOSITORY_HPP
#include <vector>
using namespace std;
class FunctionsRepository {
private:
static vector<double *> pointerToFunctions;
public:
static void addFunction(double * wsk);
};
#endif
//FunctionRepository.cpp
#include "FunctionsRepository.hpp"
void FunctionsRepository::addFunction(double * wsk) {
pointerToFunctions.push_back(wsk);
}
//Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTOINS_HPP
#include "FunctionsRepository.hpp"
int constFunction(int numberOfVehicles);
void linearFunction();
void stepFunction();
#endif
//Funcctions.cpp
#include "Functions.hpp"
double constFunction(double numberOfVehicles){
return numberOfVehicles/2;
}
double (*funcConstant)(double) = constFunction;
//ERROR HERE
FunctionsRepository::addFunction(funcConstant);
I want to add new functions to program as easily as its possible and use it leater in other parts of program.
But I dont get it. Why i am getting this error. The addFunction() method is static, that means I can use it in other classes or parts of program. Vector is static to make sure that is the only one copy for whole program.
Use function wrapper. std::function can stores callable objects. So, your code will contain something like this:
class FunctionsRepository {
private:
// void() - function prototype
static std::vector<std::function<void()>> pointerToFunctions;
public:
static void addFunction(std::function<void()> wsk)
{
pointerToFunctions.push_back(wsk);
}
};
for more information consult official documentation: http://en.cppreference.com/w/cpp/utility/functional/function
I solved It. I received an error because I was calling the FunctionsRepository::addFunction(funcConstant); expression out of any scope. I just created new function to execute this command and thats all.

structures in vs 2010 [duplicate]

I have multiple classes in my program.
A) When I create an object of a class in another class I am getting no error but when I use the object to call a function I get the above error.
B)Also if I create an object of another class and call a function using that in the constructor of my class then I get no error like this.
C) Cout function does not work in the body of the class except when I put it any function
D) The main class is able to do all of these and I am not getting any error.
It would be great to hear back soon. Thank you in advance.
Following is the code : These are two classes in my cpp. I am facing no problems except using object after creating it. the code is too huge too be posted. Everything can be done in main but not in other classes why?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
class Message
{
public:
void check(string side)
{
if(side!="B"&&side!="S")
{
cout<<"Side should be either Buy (B) or Sell (S)"<<endl;;
}
}
};
class Orderbook
{
public:
string side;
Orderbook() //No Error if I define inside constructor
Message m; //No Error while declaring
m.check(side); //Error when I write m. or m->
};
This is a mistake:
m.check(side);
That code has to go inside a function.
Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables.
In C++, code can only appear inside function bodies or in variable initializes.
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :-->
(inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class

This declaration has no storage class or type specifier in C++

I have multiple classes in my program.
A) When I create an object of a class in another class I am getting no error but when I use the object to call a function I get the above error.
B)Also if I create an object of another class and call a function using that in the constructor of my class then I get no error like this.
C) Cout function does not work in the body of the class except when I put it any function
D) The main class is able to do all of these and I am not getting any error.
It would be great to hear back soon. Thank you in advance.
Following is the code : These are two classes in my cpp. I am facing no problems except using object after creating it. the code is too huge too be posted. Everything can be done in main but not in other classes why?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
class Message
{
public:
void check(string side)
{
if(side!="B"&&side!="S")
{
cout<<"Side should be either Buy (B) or Sell (S)"<<endl;;
}
}
};
class Orderbook
{
public:
string side;
Orderbook() //No Error if I define inside constructor
Message m; //No Error while declaring
m.check(side); //Error when I write m. or m->
};
This is a mistake:
m.check(side);
That code has to go inside a function.
Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables.
In C++, code can only appear inside function bodies or in variable initializes.
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :-->
(inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class

Classes included within main() method

If I have some code like
main(int argc, char *argv[])
{
...
#include "Class1.H"
#include "Class2.H"
...
}
Generally the main() method is the starting point of every application and the content within main() is to be executed. Am I right in the assumption that the content of all classes included into main() will be executed when main() is started?
greetings
Streight
No, no, NO.
First of all, you don't #include a file within a function. You #include a file at the beginning of a file, before other declarations. OK, you can use #include anywhere, but you really just shouldn't.
Second, #include doesn't execute anything. It's basically just a copy-paste operation. The contents of the #included file are (effectively) inserted exactly where you put the #include.
Third, if you're going to learn to program in C++, please consider picking up one of our recommended texts.
You commented:
I am working with the multiphaseEulerFoam Solver in OpenFoam and
inside the main() of multiphaseEulerFoam.C are classes included. I
assume that the classes have the right structure to be called in
main()
That may be the case, and I don't doubt that the classes have the right structure to be called from main. The problem is main will be malformed after the #includes because you'll have local class definitions and who knows what else within main.
Consider this. If you have a header:
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
And you try to include this in main:
main.cpp
int main()
{
#include "foo.h"
}
After preprocessing the #include directive, the resulting file that the compiler will try to compile will look like this:
preprocessed main.cpp
int main()
{
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
}
This is all kinds of wrong. One, you can't declare local classes like this. Two, Foo won't be "executed", as you seem to assume.
main.cpp should look like this instead:
#include "foo.h"
int main()
{
}
#define and #include are just textual operations that take place during the 'preprocessing' phase of compilation, which is technically an optional phase. So you can mix and match them in all sorts of ways and as long as your preprocessor syntax is correct it will work.
However if you do redefine macros with #undef your code will be hard to follow because the same text could have different meanings in different places in the code.
For custom types typedef is much preferred where possible because you can still benefit from the type checking mechanism of the compiler and it is less error-prone because it is much less likely than #define macros to have unexpected side-effects on surrounding code.
Jim Blacklers Answer # #include inside the main () function
Try to avoid code like this. #include directive inserts contents of the file in its place.
You can simulate the result of your code by copy-pasting file content from Class1.H and Class2.H inside the main function.
Includes do not belong into any function or class method body, this is not a good idea to do.
No code will be executed unless you instantiate one of your classes in your header files.
Code is executed when:
Class is instantiated, then it's constructor method is called and the code inside the method is executed.
If there are variables of a class type inside your instantiated class, they will too run their constructors.
When you call a class method.
Try this example:
#include <iostream>
using namespace std;
int main()
{
class A
{ public:
A() { cout << "A constructor called" << endl; }
};
// A has no instances
class B
{ public:
B() { cout << "B constructor called" << endl; }
void test() { cout << "B test called" << endl; }
} bbb;
// bbb will be new class instance of B
bbb.test(); // example call of test method of bbb instance
B ccc; // another class instance of B
ccc.test(); // another call, this time of ccc instance
}
When you run it, you'll observe that:
there will be no instance of class A created. Nothing will be run from class A.
if you intantiate bbb and ccc, their constructors will be run. To run any other code you must first make a method, for example test and then call it.
This is an openFoam syntax he is correct in saying that open Foam treats #include like calling a function. In OpenFoam using #include Foo.H would run through the code not the class declaration that is done in a different hierarchy level. I would recommend all openFoam related question not be asked in a C++ forum because there is so much stuff built onto C++ in openFoam a lot the rules need to be broken to produce a working code.
You're only including declarations of classes. To execute their code, you need to create class instances (objects).
Also, you shouldn't write #include inside a function or a class method. More often than not it won't compile.

What does *New() mean when declaring member function?

I'm working on a VTK program and have found a class (specifically this one: Image Region) which i need to incorporate into my code. To do so I have made a separate ImageRegion.h and ImageRegion.cpp files so they can be easily included in the project. My Problem here is the
static vtkBorderCallback *New()
function which i do not know how to implement in the .cpp file or, to be quite honest, what purpose it serves at all. What does it do? Is it even necessary to have it?
When compiling I get the error:
/home/Desktop/test/src/ImageRegion.cpp:7:10: error: ‘vtkBorderCallback::vtkBorderCallback’ names the constructor, not the type
My .h file:
//ImageRegion.h
#pragma once
#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkAssemblyNode.h>
#include <vtkAssemblyPath.h>
#include <vtkBorderRepresentation.h>
#include <vtkCommand.h>
#include <vtkCoordinate.h>
#include <vtkImageMapper3D.h>
#include <vtkImageActor.h>
#include <vtkInteractorStyleImage.h>
#include <vtkPolyData.h>
#include <vtkPropPicker.h>
#include <vtkProperty2D.h>
#include <vtkBorderWidget.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
class vtkBorderCallback : public vtkCommand
{
public:
vtkBorderCallback();
static vtkBorderCallback *New();
virtual void Execute(vtkObject *caller, unsigned long, void*);
void SetRenderer(vtkSmartPointer<vtkRenderer> ren);
void SetImageActor(vtkSmartPointer<vtkImageActor> im);
double coords[6];
private:
vtkSmartPointer<vtkRenderer> Renderer;
vtkSmartPointer<vtkImageActor> ImageActor;
};
And my .cpp file:
//ImageRegion.cpp
#include "ImageRegion.h"
vtkBorderCallback::vtkBorderCallback(){}
static vtkBorderCallback::vtkBorderCallback* New()
{
return new vtkBorderCallback;
}
void vtkBorderCallback::Execute(vtkObject *caller, unsigned long, void*)
{
//Do stuff, from original VTK example code
}
void vtkBorderCallback::SetRenderer(vtkSmartPointer<vtkRenderer> ren) {this->Renderer = ren;}
void vtkBorderCallback::SetImageActor(vtkSmartPointer<vtkImageActor> im) {this->ImageActor = im;}
Any help is much appreciated.
This
static vtkBorderCallback *New();
is a static member function called New, taking no arguments, and returning a pointer to vtkBorderCallback.
In the implementation, you should omit the static. You also need to place the function in the scope of its class:
vtkBorderCallBack* vtkBorderCallback::New()
{// ^^^^^^^^^^^^^^^^^^^
return new vtkBorderCallback; // danger! Caller needs to delete this eventually
}
In VTK nearly all of the classes derive from vtkObjectBase. They should use New() and Delete() to create and delete the objects (the constructor and destructor are protected). These methods include referencing counting to make sure that they get properly shared among other vtkObjects that may use them. There is a VTK macro (vtkStandardNewMacro) that takes care of the implementation of New() and the base class implements Delete(). So for VTK, the best way to implement the static New() method is to use that macro. For your class called vtkBorderCallBack it would look like:
vtkStandardNewMacro(vtkBorderCallBack);
This should go in your .cpp file.
To solve the error, put vtkBorderCallBack:: before New():
vtkBorderCallBack* vtkBorderCallBack::New()
~~~~~~~~~~~~~~~~~~~
{
...
}
He should not omit static since New() is meant as constructor. In this scenario I would rather expect the real constructor to be private. The implementation
static vtkBorderCallback::vtkBorderCallBack* New()
{
return new vtkBorderCallback;
}
is syntactically wrong. It has so be
vtkBorderCallBack* vtkBorderCallback::New()
{
return new vtkBorderCallback;
}
Finally the whole approach is strange. New() is not really required here, and possibly leads to a memory leak. To establish a class-specific memory management overload operators new and delete on a per-class basis. Alternatively, to prevent leaks, do not return a raw pointer; return std::auto_ptr (deprecated) or std::unique_ptr:
std::unique_ptr<vtkBorderCallBack> vtkBorderCallback::New()
{
return std::unique_ptr<vtkBorderCallBack>(new vtkBorderCallback); // uses move c'tor
}
However, std::unique_ptrs are movable but not copyable. But that's the point when leaks have to be prevented. When the pointer returned by New() is spreaded all over the code better use a std::shared_ptr.
If you have only a C++03 compiler I recommend Herb Sutter's Using auto_ptr Effectively.