function calling within a class C++ - c++

Within the same class I have
Executive::Executive(std::istream& fin){
std::ifstream dFin(argv[2]);
if(!dFin.is_open()){
std::cout <<"Could not open directives file.";
std::cout <<endl;
}
else{
std::string directive;
dFin >>directive;
int x;
dFin >>x;
if(directive=="print"){
}
and the function
void Executive::print(int i) const{
if(i>MAX_NUM_POLYNOMIALS){
std::cout <<"Sorry, " <<i <<" is not within the known polynomials.";
std::cout <<endl;
}
else{
pNom[i].print(std::cout);
std::cout << i <<'\n';
}
}
In the last bit of the first code, how do I call the print function from the second code? They're in the same class, and I don't want to confuse calling it with the print function being called from another class in the second part.

In short, there is no problem in calling the print method directly in here. There are some scenarios below though for consideration.
If you have a print method in a different class, you would simply use myAnotherClass.print(...).
If you need to call a print method explicitly from the base class, you can use the base class scope explicitly as presented in the example at the bottom, such as MyBaseClass::print(...)
It is a simple case when you cannot have any clash except if you have a print method in the global scope or a namespace being used.
If it is in the global area, you would call it with ::print(...), and if it is in a namespace, you could use myNamespace::print(...)
Try to avoid "this->" at all costs, and leave that as the last resort. If you had a 'print' argumnt in the method where you are calling print, that could be one case if you could not change the argument name otherwise for some reason.
Finally, after the theoretical lesson, here goes the practical example:
Executive::Executive(std::istream& fin){
std::ifstream dFin(argv[2]);
if(!dFin.is_open()){
std::cout <<"Could not open directives file.";
std::cout <<endl;
}
else{
std::string directive;
dFin >>directive;
int x;
dFin >>x;
if(directive=="print") {
print(x); // calling the method of the current class
MyBaseClass::print(x); // calling the method of the base class
myAnotherClass.print(x); // classing the method of a different class
::print(x); // calling print in the global scope
myNamespace::print(x); // calling the method in a dedicated namespace
}

If you want to be ABSOLUTELY sure you're calling your own function you can use the this keyword if it's not a static function or the class name if it is static.
this->print(...); or Executive::print(...);

You can just fully qualify the member function to call:
Executive::Executive(std::istream& fin)
{
// ...
if(directive == "print")
{
Executive::print(x);
}
// ...
}
I should note that if you're adding a non-static print method to another different class there is no chance of a name collision here. That's because to actually call that method from outside of its containing class you have to refer to some instance to call it with.

Related

function not called with the same name as a class

Why the function bellow void i( ) is not called as in a 'Normal' function.
void i(){
cout << 10 << endl;
}
int main(){
class i {
int j;
};
i();//
return 0;
}
The normal behavior expected is to print 1O, but I did not getting anything, not a compiler warning nor the result.
The inner i is shadowing the outer one. You are calling the default constructor of class i which does nothing in this case.
The solution is to explicitly scope the call, as ::i();
Because it's trying to call "i" in the current scope:
You can call your function::i();

Not able to use function variables ? Error expression must have class type

Hey i want to use the function wolves variable in the storyline and im trying to do this :
"\nYou awake on a beach to the sound of"<< Wolves().name; " starving and blood hungry,"
"\nThere is a Rock on the ground. You pick it up";
inventory.push_back("Rock");
But Wolves().name; there is an error as mentioned in the title. Why cant i do this?
Here is the code for the function Wolves:
void Wolves()
{
string name = "Wolves";
int health = 20;
hitPoints() +1;
}
You can't access variables defined in a function from outside the function in C++, but you can change it to a class:
class Wolves {
public:
string name;
// ...
Wolves(); // Constructor
//...
}
To access it you can use
Wolves wolve;
wolve.name = "whateverName"; // or set it in the constructor
cout << wolve.name << endl;
What you did in there is create local variables within the function. Once the function exits, they no longer exist. What you want to do is make a Wolves class and create public member variables to do what you want. For an example,
class Wolves {
public:
string name;
int health;
Wolves(string name, int a);
}
Then on the main function,
Wolves w("Bob", 20);
cout << "The name is: " << w.name << endl;
Will output "The name is: Bob"
void functions don't really do anything unless you pass the value in by reference. If you want to alter the object via void function, you should do something like
void Wolves(Wolves & wolfToChange)
{
wolfToChange.name = "Bob";
}
and that will directly alter the object.
You declared "name" as a local variable in a function called Wolves(), but the code that you were referring to expects the function Wolves() to return an object that has an accessible member name. That is why the compiler is complaining.
The way you wrote the code suggests that Wolves should be a class or struct, not a function.

C++ geting error while using function inside class

I can't figure out why I get this error: "the function was not declared". I am still a newbie at programming, but I am trying my best to learn it!
so here is my code, I would be realy greatful if you could help me:
main:
#include <iostream>
#include <vector>
#include "szovegkezelo.h"
using namespace std;
int main()
{
string sz;
beolvas(sz);
kiir(sz);
return 0;
}
header:
#ifndef SZOVEGKEZELO_H_INCLUDED
#define SZOVEGKEZELO_H_INCLUDED
#include <iostream>
using namespace std;
class szovegkezelo {
protected:
string sz;
public:szovegkezelo
void beolvas(string &sz);
void kiir(string t);
};
#endif // SZOVEGKEZELO_H_INCLUDED
cpp:
#include "szovegkezelo.h"
#include <iostream>
void szovegkezelo::beolvas(string &sz)
{
getline(cin, sz);
}
void szovegkezelo::kiir(string t)
{
cout << "a beadott szoveg: " << t << endl;
cout << "a string hossza: " << t.size() << endl;
}
From what it looks like, you are trying to call a classes function (method) called 'beolvas' from 'main' but because it belongs to a class, you can't call it like that, you need to create an instance of that class and call the method on that instance, or make the function static and call it from the class.
Your first option is to create an instance of the class and then call the methods on the class like so:
int main()
{
string sz;
szovegkezelo szov;
szov.beolvas(sz);
svoz.kiir(sz);
return 0;
}
Your second option is to make the functions in your class static, this way they will not need an instance of the class to be called:
int main()
{
string sz;
szov::beolvas(sz);
svoz::kiir(sz);
return 0;
}
static void szovegkezelo::beolvas(string &sz)
{
getline(cin, sz);
}
static void szovegkezelo::kiir(string t)
{
cout << "a beadott szoveg: " << t << endl;
cout << "a string hossza: " << t.size() << endl;
}
Been a while since I've done anything static in c++ so please correct me if I've done something wrong in the second option.
Your two or more data types... error comes from a misuse of...something...after that public access specifier.
Change this:
public:szovegkezelo
to this:
public:
If you're trying to make a constructor, it needs to be declared like any other function, minus the return type.
Your other error occurs because this function was declared improperly.
Other than that, you need to create an object before you can call the class's functions. Each object has it's own set of variables that the functions work on. I would seriously recommend reading a good beginner C++ OOP book.
Somewhere in main, you need to create an object:
szovegkezelo myObject;
Then, use it to call functions:
myObject.kiir (sz);
Finally, note that your data members should typically be declared with the private access specifier. protected has nothing to do with normal classes that are not inherited from.
couple of things :
1) In main you have not instantiated an object of szovegkezelo and you are trying to call beolvas . Compiler is looking for a free function beolvas whereas you have declared beolvas as member function
2) public:szovegkezelo is not right if you are looking for a default constrcutor that does nothing don't have that line else if you need to do something specific with default construct declare it as szovegkezelo() in header.
3) as mentioned in comments it is not a good practice to put
using namespace std in header files or any using namespace

Why prototype is required even without any class declaration?

If I just do it:
Ex1:
#include <iostream>
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
I get compilation error! Because the compile doesn´t know what is "doSomething".
But if I change the position of doSomething to come in first place, the program compiles successfully.
Ex2:
#include <iostream>
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
int main()
{
//try to call doSomething function
doSomething();
}
I can declare prototype to be like this:
Ex3:
#include <iostream>
void doSomething(void);
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
But why the first example does not work? Why I even have to declare a prototype or call functions first and main function at last?
Thanks!
You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.
Because the compiler hasn't seen doSomething before it's used.
Either you must prototype it, or define it first, so that the compiler knows how to analyze the usage of it.
This is a legacy from C. C is a single pass language which means that it has to do everything by only reading the file once. To be able to call a function without a forward declaration/prototype would require reading the file twice; The first time to find all the function signatures and the second time to actually compile.
C++ kept this requirement for features that were part of C, such as free functions and global variables. However classes are new to C++ and there was no need to keep the old way of doing things. So within a single class definition, multi-pass compilation is used. That's why you can do this:
class MyClass {
void foo() {bar();}
void bar() {}
};
But you can't do what you listed in your question.

C++ passing const string references in methods?

I'm trying to initialize a private variable of my Class passing a const string &aString to it as parameter.
Here's my method:
void Image::initWithTextureFile(const std::string &inTextureName)
{
Texture2D *imTexture = TEXTURE_MANAGER->createTexture(inTextureName);
if(imTexture)
{
texture = imTexture;
scale = 1.0f;
name = inTextureName; //name is a private string variable inside my class
initImplementation();
}else {
printf("Could not load texture when creating Image from file %s\n",inTextureName.c_str());
}
}
My problem is the following, when I call this method I do it like:
myInitializer.initWithTextureFile("myFile.bmp");
When I'm inside the scope of initWithTextureFile the name variable takes the value of inTextureName. For this example if I cout << name << endl; inside initWithTextureFile i would get "myFile.bmp"
But when I leave the scope of the function, name looses it's value, so when i cout << name << endl; I get nothing printed in the console.
Could anyone point me out to what's going on here?
Name is declared:
private:
std::string name;
If you're outside the class scope, and cout << name compiles at all, it means you have another variable named name, and that's what's being picked up. If you want to refer to it outside the class, you'll have to come up with a way that will export it. You might, for example, have a member function like const std::string &GetName() { return name; }.
You either omitting something in your description or are not showing appropriate code that could help solve your problem.
This works:
#include <iostream>
#include <string>
using namespace std;
struct A
{
void f(const string& str) { name = str; }
void g() { cout << name << endl; }
string name;
};
int main()
{
A a;
a.f("test");
a.g();
}
Output:
test
That should work. Are you sure it is not being modified somewhere else, such as in initImplementation?
The problem probably have to do with the name variable : is it a pointer or ref to string instead of a plain string ?
The only reasonable explanation here is that you must be working with two different name objects. The one you declared as a class member should hold its value when you exit the method. It is just that outside the class method you must be printing a completely different name, which is empty.
I was going to say something about short-lived stack objects but I realised that was wrong. What it could be is something to do with exporting the containing class from a DLL.
If so, you might find a warning like this:
c:\yourclass.h(7): warning C4251: 'YourClass::name_' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'YourClass'
This thread describes more.
How is 'name' declared? It seems like maybe it's declared as a reference instead of an object.
Try:
name = std::string(inTextureName);