Null output in using class methods - c++

In following code I get no output from directly calling sumit() function, but when I call it through the other function displayIt() (which calls sumit() ), it displays the output. How can I fix it? And please also explain what is happening?
#include<iostream>
#include<string>
using namespace std;
template <typename C>
class ABC
{
private:
C num1, num2;
public:
ABC(C a, C b)
{
num1 = a;
num2 = b;
}
void displayIt()
{
cout << "A+B:" << sumit() << endl;
}
C sumit() { return num1 + num2; }
};
int main()
{
ABC<int> o1(2, 3);
ABC<string> o2("ABC", "XYZ");
//It doesn't display aything...
cout << "Call-1: " << endl;
o1.sumit();
o2.sumit();
//It displays the output...
cout << "Call-2: " << endl;
o1.displayIt();
o2.displayIt();
system("pause");
}

Of course you get no output , because this method isn't trying to print anything . It simply returns a number.
Either do this in main :
cout << o1.sumit() << endl;
cout << o2.sumit() << endl;
Which will directly print the value returned from this method.
Or add the same logic of displayIt to sumit .
BTW - This question is irrelevant to C++ Template . The same behaviour would have happened in a regular class .

Related

CPP Guessing Game not working, its stops after i enter the name

I'm trying to make this kina guess game on C++, I'm a beginner and still learning.
What I'm trying to achieve is a guessing game of two const names, is very simple without errors but it's not working after I enter something. it should report until I find the correct name. Please also I don't want to change the structure of the code, just find why isn't working.
#include <iostream>
#include <string>
using namespace std;
struct Vlerat {
string guess01 = "Resul";
string guess02 = "Rejan";
int numruesi = 0;
};
int main() {
Vlerat funksioni;
string nameGuess;
int nameOkay = 0;
cout << "Gjej njerin prej dy emrava te fshehura." << endl;
cout << "Ndihm: Fillojn me Shkronjen 'R', dhe pas asaj vjen edhe nje shkronj 'e'" << endl;
do {
cout << "Shkruaj Emrin > "; cin >> nameGuess;
if (nameGuess == funksioni.guess01){
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
if (nameGuess == funksioni.guess02) {
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
funksioni.numruesi++;
} while(nameOkay = 0);
}
You should change while(nameOkay = 0); to while(nameOkay == 0);.
Because = is an assignment, but == is operator of comparing (equality)
Read about it here
And here

structure and functions in C++

Can someone explain why this code gives the output 10? When I try to analyse it my logic gives as result 11.
#include <iostream>
using namespace std;
class A {
public:
A() { a.a = a.b = 1; }
struct { int a,b; } a;
int b(void);
};
int A::b(void) {
int x=a.a;
a.a=a.b;
a.b=x;
return x;
};
int main(void) {
A a;
a.a.a = 0;
a.b();
cout << a.b() << a.a.b << endl;
return 0;
}
In the cout line, a.b() could either be called before or after a.a.b is evaluated. Beginners sometimes assume left-to-right evaluation in this sort of code but actually that is not a rule of C++.
Those two different possibilities would explain your 10 and 11. To avoid ambiguity you could write:
cout << a.b();
cout << a.a.b << endl;
(assuming that order was your intent).
Note: C++17 may change this and define left-right evaluation order for this code.
Other than using a debugger, you can also use cout statements to help keep track of when things are called.
To kind of help myself out tracing your program I fixed a bit of the indentation and added comments as to when things are happening:
#include <iostream>
using namespace std;
class A {
public:
A() {
a.a = a.b = 1;
}
struct {
int a,b;
} a;
int b(void);
};
int A::b(void) {
cout << "Within A::b()" << endl;
// swap a.a, a.b
int x=a.a;
a.a=a.b;
a.b=x;
cout << "a.a.a = " << a.a << " a.a.b: " << a.b << endl;
return x;
};
int main(void) {
// sets a.a.a = 1, a.a.b = 1
A a;
// sets a.a.a = 0, a.a.b = 1
a.a.a = 0;
// a.a.a = 1, a.a.b = 0
a.b();
// check output here
cout << a.b() << a.a.b << endl;
return 0;
}
The above program results with the following output on http://cpp.sh/ :
Within A::b()
a.a.a = 1 a.a.b: 0
Within A::b()
a.a.a = 0 a.a.b: 1
10
In all, it depends on whether or not a.b() or a.a.b is resolved first when you call cout. In this case, operator precedence is undefined due to how cout works. This stackoverflow post has some good info on this.

How is "a" used in my program?

new to learning c++ and I was wanting to understand the program ive practiced. I have a section of code I want to understand but im kind of lost.
#include "stdafx.h";
#include <iostream>;
// getValueFromUser will read a value in from the user, and return it to the caller
int getValueFromUser()
{
std::cout << "Enter an integer: ";
int a;
std::cin >> a;
return a;
}
int main()
{
int x = getValueFromUser(); // first call to getValueFromUser
int y = getValueFromUser(); // second vall to getValueFromUser
std::cout << x << " + " << y << " = " << x + y << std::endl;
return 0;
}
Im just wanting to know how " int a " comes into play here. If someone could help it would be appreciated.
You declare an uninitialized variable of type int with identifier a:
int a;
The user provides a value to a.
std::cin >> a;
A copy is returned from the function:
return a;
Calls to the getValueFromUser() will create a temporary a,
assign it to user input, and return it each time.
In c++ you have to declare variable (providing the type and name) before it's first use.
std::cin has to put it's output somewhere and that's why you need this additional variable.

C++ Can't figure out output for a class that holds player information. It outputs garbage

I've been pulling my hair out trying to figure out this program. The class has to hold 3 player's info and output their info. My output function is not outputting from my set/get functions. Also, if I output the array indexes the program crashes (that's the array indexes are commented out in the Output function).
edit: I'll just show one profile to keep the code smaller
Any help is appreciated.
#include <cstdlib>
#include <iostream>
using namespace std;
class PlayerProfile
{
public:
void output();
void setName1(string newName1); //player's name
void setPass1(string newPass1); //player's password
void setExp1(int newExp1); //player's experience
void setInv1(string newInv1[]); //player's inventory
void setPos1(int newX1, int newY1); //player's position
string getName1();
string getPass1();
int getExp1();
string getInv1();
int getPos1();
private:
string name1;
string pass1;
int exp1;
string inv1[];
int x1;
int y1;
};
int main(int argc, char *argv[])
{
PlayerProfile player;
cout << "This program generates three player objects and displays them." << endl;
cout << endl;
player.output();
system("PAUSE");
return EXIT_SUCCESS;
}
void PlayerProfile::setName1(string newName1)
{
newName1 = "Nematocyst";
name1 = newName1;
}
void PlayerProfile::setPass1(string newPass1)
{
newPass1 = "obfuscator";
pass1 = newPass1;
}
void PlayerProfile::setExp1(int newExp1)
{
newExp1 = 1098;
exp1 = newExp1;
}
void PlayerProfile::setInv1(string newInv1[])
{
newInv1[0] = "sword";
newInv1[1] = "shield";
newInv1[2] = "food";
newInv1[3] = "potion";
inv1[0] = newInv1[0];
inv1[1] = newInv1[1];
inv1[2] = newInv1[2];
inv1[3] = newInv1[3];
}
void PlayerProfile::setPos1(int newX1, int newY1)
{
newX1 = 55689;
x1 = newX1;
newY1 = 76453;
y1 = newY1;
}
string PlayerProfile::getName1()
{
return name1;
}
string PlayerProfile::getPass1()
{
return pass1;
}
int PlayerProfile::getExp1()
{
return exp1;
}
string PlayerProfile::getInv1()
{
return inv1[0], inv1[1], inv1[2], inv1[3];
}
int PlayerProfile::getPos1()
{
return x1, y1;
}
void PlayerProfile::output()
{
cout << "Player Info - " << endl;
cout << "Name: " << name1 << endl;
cout << "Password: " << pass1 << endl;
cout << "Experience: " << exp1 << endl;
cout << "Position: " << x1 << ", " << y1 << endl;
cout << "Inventory: " << endl;
/*cout << inv1[0] << endl;
cout << inv1[1] << endl;
cout << inv1[2] << endl;
cout << inv1[3] << endl; */
}
This is the output that I am getting:
This program generates three player objects and displays them.
Player Info -
Name:
Password:
Experience: -2
Position: 3353072, 1970319841
Inventory:
Press any key to continue . . .
I'm sorry if I sound like an idiot, this is the first time I have programmed with classes and I am very confused.
First:
You do not have a constructor declared or defined in your class so when you compile, the compiler provides you with a default constructor.
The line
PlayerProfile player;
calls the default constructor provided by the compiler. This default constructor only allocates memory for your class member variables, but does not set their values. This is why name1, pass1, exp1, x1, y1 are not outputting what you expect.
Second:
C++ will not call get or set functions for you, and I think you are misunderstanding how c++ functions work.
this
void PlayerProfile::setName1(string newName1)
{
name1 = newName1;
}
is a function definition. You do not need to assign newName1 inside the function. It's value is passed to the function when a line like
setName1("Nematocyst");
is executed.
If you write a constructor, you can use it to call your set functions, and pass them the values you want to set member variables to.
If you do not want to write a constructor, you can call class functions/methods from main with:
player.setName1("Nematocyst");
Third:
Your program crashes because you are not using arrays properly. Here is a tutorial on how to declare an array and access it's contents.
Generally, I think you are trying to run before you know how to walk. Try not to get frustrated. Learn how arrays work, how functions work, and then how classes work. I hope this is not your homework assignment!

Are structure members of structure passed by reference, passed ONLY by value?

My module tries to do things along the lines of the following program: sub-functions try to modify a structure's elements and give it back to the function to whom the structure is passed by reference.
#include <iostream>
#include <vector>
using namespace std;
struct a
{
int val1;
vector<int> vec1;
};
struct a* foo();
void anotherfunc(struct a &input);
int main()
{
struct a *foo_out;
foo_out = foo();
cout<< "Foo out int val: "<< foo_out->val1<<"\n";
cout<< "Foo out vector size: "<< foo_out->vec1.size()<< "\n";
cout<< "Foo out vector value1: "<< foo_out->vec1.at(0)<< "\n";
cout<< "Foo out vector value2: "<< foo_out->vec1.at(1)<< "\n";
return 0;
}
struct a *foo()
{
struct a input;
input.val1=729;
anotherfunc(input);
return &input;
}
void anotherfunc(struct a &input)
{
input.vec1.push_back(100);
input.vec1.push_back(1000);
input.vec1.push_back(1024);
input.vec1.push_back(3452);
cout<< "Anotherfunc():input vector value1: "<< input.vec1.at(0)<< "\n";
cout<< "Anotherfunc():input vector value2: "<< input.vec1.at(1)<< "\n";
cout<< "Anotherfunc():input int val: "<< input.val1<< "\n";
}
I am expecting the main function to contain the modified integer value in structure (729), and also the vector values (100,10000,1024 and 3452). On the contrary, main has none of these values, and on g++, the program shows a strange behaviour: main() shows that there are 4 elements in the vector inside structure, but when trying to print the values, segfaults.
After some more thought, I assume my question is : "Are structure members of structure passed by reference, passed ONLY by value ?" Should I not expect that vector to have the values set by functions to whom the entire structure is passed by reference? Kindly help.
Vijay
struct a *foo()
{
struct a input;
input.val1=729;
anotherfunc(input);
return &input;
}
You are returning pointer on the local object (it will be destroyed on exit from function), so, there is dangling pointer here and your program has undefined behaviour.
As ForeEveR says, the pointer you are returning is pointing to memory which is no longer guaranteed to contain a valid object. If you want this behavior, allocate input on the heap as follows:
a * foo ()
{
a * input = new input;
input->val1 = 729;
anotherfunc (*input);
return input;
}
Now it is the responsibility of whoever calls foo to free this memory, for example
{
a * foo_out = foo();
// do stuff with foo_out
delete foo_out; foo_out = 0;
}
At some point you will realize that keeping track of who allocated which objects is tedious, when this happens you should look up "smart pointers".
First of all, there is nothing terribly magical about "structures" in C++ — you should treat them like any other type. In particular, you don't need to write the keyword struct everywhere.
So here's your code in more idiomatic C++ (also re-ordered to avoid those wasteful pre-declarations):
#include <iostream>
#include <vector>
using namespace std;
struct a
{
int val1;
vector<int> vec1;
};
void bar(a& input)
{
input.vec1.push_back(100);
input.vec1.push_back(1000);
input.vec1.push_back(1024);
input.vec1.push_back(3452);
cout << "bar():input vector value1: " << input.vec1.at(0) << "\n";
cout << "bar():input vector value2: " << input.vec1.at(1) << "\n";
cout << "bar():input int val: " << input.val1 << "\n";
}
a* foo()
{
a input;
input.val1=729;
bar(input);
return &input;
}
int main()
{
a* foo_out = foo();
cout << "Foo out int val: " << foo_out->val1 << "\n";
cout << "Foo out vector size: " << foo_out->vec1.size() << "\n";
cout << "Foo out vector value1: " << foo_out->vec1.at(0) << "\n";
cout << "Foo out vector value2: " << foo_out->vec1.at(1) << "\n";
}
Now, as others have pointed out, foo() is broken in that it returns a pointer to a local object.
Why all the pointer trickery? If you're worried about copying that vector, then you can dynamically-allocate the a object and use a shared pointer implementation to manage that memory for you:
void bar(shared_ptr<a> input)
{
input->vec1.push_back(100);
input->vec1.push_back(1000);
input->vec1.push_back(1024);
input->vec1.push_back(3452);
cout << "bar():input vector value1: " << input->vec1.at(0) << "\n";
cout << "bar():input vector value2: " << input->vec1.at(1) << "\n";
cout << "bar():input int val: " << input->val1 << "\n";
}
shared_ptr<a> foo()
{
shared_ptr<a> input(new a);
input->val1 = 729;
bar(input);
return input;
}
Otherwise, just pass it around by value.