I understand that void returns no values.
So how does it work in conjuncture to a function?
My understanding is that the purpose of a function is to return a piece of information after doing something with it.
so why would I want to return no value, and how would this be beneficiary?
My understanding is that the purpose of a function is to return a
piece of information after doing something with it.
In some (most of the) programming languages, functions have side effects also. Purpose of some functions is limited only to side effects and return value is not necessary. Such functions have void return type.
Some examples of side effects may be:
Update a global
File operation, logging etc where user doesn't want to know the status of operation
Freeing resources
C++ Programming Language Stroustrup 4th Edition book
When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. However, that would make a mess of the grammar (§iso.A). Consequently, void is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value.
Edit:
When you don't expect something in return to the calling function, we use void function.
If void() does not return a value, why do we use it?
It can be pretty useful for modularizing output.
I'll provide you with an example:
#include <iostream>
#include <string>
using namespace std;
void displayMessage(string fName, string mName, string lName, string id);
int main() {
string student[4] = { "Mike", "L.", "Jason", "c23459i" };
displayMessage(student[0], student[1], student[2], student[3]);
return 0;
}
void displayMessage(string fName, string mName, string lName, string id)
{
double PI = 3.14159265359;
cout << "Student " << " information:"
<< "\nFirst name: " << fName
<< "\nMiddle Initial: " << mName
<< "\nFirst name: " << lName
<< "\nID: " << id
<< "\nThe Circumference of a circle with the radius of 2: " << (2*PI*2);
}
You can use void functions IF you don't need to return a value. If you plan to do calculations and return a value such as an int, use a function declaration with the return type of int.
Related
so I'm kinda new to c++ (actually very new) and I was messing around with my code:
#include <iostream>
using namespace std;
string aString()
{
cout << "Car" << endl;
}
int main()
{
cout << "Word:" << aString() << endl;
return 0;
}
I tried to get something like: "Word: Car".
It ended up not working and showing a bunch of weird characters. My question is can a function return a string like an integer does?
Sorry if this is a stupid question.
My question is can a function return a string like an integer does?
Sure, you want to write
string aString()
{
return "Car";
// ^^^^^^
}
If the function declares a return type, you actually need to return something, otherwise you have undefined behavior.
The compiler should have issued a warning about that.
std::cout is used to print out values at the terminal, not to return them from functions.
I want to output the values of the private class members Bankcode and AgentName. How can I do this from within my main() function, or in general, outside of the BOURNE class.
My initial code attempts are below:
#include <iostream>
#include <string>
using namespace std;
class BOURNE
{
string Bankcode ={"THE SECRET CODE IS 00071712014"} ; /*private by default*/
string AgentName={"Jason Bourne"}; /*private by default*/
public:
void tryToGetSecretCodeandName(string theName ,string theCode); //trying to get the private
void trytoGetAgentName( string name); // try to get name
};
//***********************defining member function**************************************
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode) //member defining function
{
Bankcode=theCode; //equalling name to the code here
AgentName=theName; //the samething here
cout<<theCode<<"\n"<<theName; //printing out the values
}
//************************main function*****************************
int main()
{
BOURNE justAnyObject; //making an object to the class
justAnyObject.tryToGetSecretCodeandName();
return 0;
}
Third Answer
Your code has two 'getter' style functions, but neither one takes no arguments. That is, both of your functions require arguments to be passed.
Your main function is calling get...CodeandName(), which has no arguments. As such, you get a compiler error, probably complaining about valid signatures, or arguments passed.
Edited Answer
If you only want to get the values, the typical (as far as I am aware) implementation is something like
std::string BOURNE::getCode()
{
return Bankcode;
}
std::string BOURNE::getName()
{
return AgentName;
}
int main()
{
BOURNE myAgent;
cout<< "The agent's name is : " << myAgent.getName() << endl;
cout<< "The agent's code is : " << myAgent.getCode() << endl;
}
Original Answer, left in because I feel like it's more useful
I suspect what you're asking is if you could do something like
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode)
{
if (Bankcode == theCode) {
cout<< "You correctly guessed the code : " << Bankcode << endl;
}
if (AgentName == theName) {
cout << "You correctly guessed the agent's name : " << AgentName << endl;
}
}
This will allow you to repeatedly guess at the name, and get output when you're correct.
If you wanted to disable this kind of guessing, then you could consider creating a new class (possibly derived from/based on std::string - but see this question for reasons to be careful!) and implement an operator== function which always returned false.
Just beginning to learn about structs, I thought I understood how they work, using the dot operator to access a member of an object, but i clearly don't as the readEmployeeRecord function below doesn't work at all. How should i be doing this? (the code is short and self explantory)
Many thanks for taking the time to further explain structs to me! Naturally I tried google first but i couldn't find an example that inputted data quite the way i wanted and wasn't sure how i should be going about it.
#include <iostream>
#include <iomanip>
using namespace std;
//Employee type
struct Employee{
float wage;
char status;
char dept[4]; //for 3letter department, last position is \0 correct?
};
//function definitions
void readEmpoyeeRecord(Employee staff);
void printEmployeeRecord(Employee staff);
int main(){
Employee employeeA;
readEmpoyeeRecord(employeeA);
printEmployeeRecord(employeeA);
return 0;
}
void readEmpoyeeRecord(Employee employee){
cout << "Enter empolyees wage: ";
cin >> employee.wage;
cout << "Enter empolyees status (H or S): ";
cin >> employee.status;
cout << "Enter empolyees dept (ABC): ";
cin >> employee.dept;
}
void printEmployeeRecord(Employee staff){
cout << "Wage: Status: Department:" <<endl;
cout << fixed << setprecision( 2 ) << staff.wage;
}
First, try searching google for "passing parameters by reference and by value".
You'll learn that:
void readEmpoyeeRecord(Employee staff);
passes your variable to the function by value, meaning that a copy of your object is created and used inside the function, so your original object doesn't get modified, but a copy.
To get the desired result, use:
void readEmpoyeeRecord(Employee& staff);
Passing by reference means you pass that exact same object, and not a copy.
Your code will basically work like this:
//create new employee
Employee employeeA;
//call method readEmployeeRecord on a copy of employeeA
readEmpoyeeRecord(employeeA);
//call method printEmployeeRecord on a copy of employeeA
printEmployeeRecord(employeeA);
readEmpoyeeRecord(Employee employee) is copy by value, not reference, so you are loosing your changes.
Use readEmpoyeeRecord(Employee& employee) instead.
Your problem is that in C++, objects are passed by value until you specify otherwise. Thus, in the body of readEmpoyeeRecord you're dealing with a copy of employeeA, not with employeeA itself.
Pass a reference to your readEmpoyeeRecord function. The signature of readEmpoyeeRecord should read:
void readEmpoyeeRecord(Employee &employee)
I've been programming in java and AS3 and C# for some time, and decided to give C++ a try... So, I decided to create a simple program to see how objects work here. I have two files:
Human.h
#pragma once
#include <string>
#include <iostream>
using namespace std;
class Human
{
private:
int _age;
string _name;
bool _gender;
public:
void setAge(int);
void setName(string);
int getAge();
string getName();
bool getGender();
Human(int age, string name, bool gender)
{
setAge(age);
setName(name);
_gender = gender;
}
~Human()
{
}
};
int Human::getAge(){
return _age;
}
string Human::getName(){
return _name;
}
bool Human::getGender(){
return _gender;
}
void Human::setAge(int val){
}
void Human::setName(string val){
_name = val;
}
And Main.cpp
#include <iostream>
#include "Human.h"
#include <string>
using namespace std;
void main(void){
Human *me;
me = new Human(27,"Mr Miyagi",true);
cout << "My name is "+me.getName()+" and I am "+me.getAge()+" years old";
}
What I get is a red line under the "me" word, and an error C2228: left of '.getName' must have class/struct/union
me is a pointer to a Human - so you need to use ->
cout expects you to use the << operator.
main should not return void, but int.
always delete what you new
int main() {
Human *me;
me = new Human(27,"Kostas Loupasakis",true);
cout << "My name is " << me->getName() << " and I am " << me->getAge() << " years old";
delete me;
}
Alternatively, you can do without the pointer, and use .:
int main() {
Human me(27,"Kostas Loupasakis",true);
cout << "My name is " << me.getName() << " and I am " << me.getAge() << " years old";
}
The first variant above allocates a Human from the free store, called heap - similar to java. You need to explicitly delete in c++ though.
The second variant allocates a Human on stack - java can only do this with primitive types (int, float) and so on, c++ can do this with any object. In this case, me is automatically destructed when it goes out of scope, at the final '}' in main.
It should be -
cout << "My name is " << me->getName() << "and I am " << me->getAge() << " years old";
me is a pointer to an object. So, it's members should be accessed by operator ->.
Also, note that Human::setAge() function does nothing.
You have declared me as a pointer. Either remove the * on the declaration, or Use me->GetName() etc to use it.
= = = edit = = =
Since there is no default constructor, the * must remain. Either that or change it to
Human me(27, "name", true);
Others have addressed the direct problem you asked about. If you will indulge me, let me address a tangential issue.
Here is what you started with.
void main()
{
// You could combine these two lines like this:
// Human *me = new Human(27,"Kostas Loupasakis",true);
Human *me;
me = new Human(27,"Kostas Loupasakis",true);
cout << "My name is "+me->getName()+" and I am "+me->getAge()+" years old";
}
I can't speak to AS3, but in java and C#, you have the garbage collector to clean up allocated memory. There is no such beast in C++, so you have to clean up the memory yourself like this.
void main()
{
Human *me = new Human(27,"Kostas Loupasakis",true);
cout << "My name is "+me->getName()+" and I am "+me->getAge()+" years old";
delete me;
}
The call to new allocates the Human object on the heap, and delete frees the memory when you are done with it. Here is a better way to do it.
void main()
{
Human me(27,"Kostas Loupasakis",true);
cout << "My name is "+me.getName()+" and I am "+me.getAge()+" years old";
}
In this case, space for the Human object is reserved on the stack as opposed to the heap. Thus, the space is automatically reclaimed when the function exits. Additionally, you can use the . notation instead of the -> notation since you are dealing with an object as opposed to a pointer.
I hope this helps.
the object 'me' is actually a pointer, so therefore you will need to use an arrow instead of a dot.
me->getname();
will solve the error.
void outputString(const string &ss) {
cout << "outputString(const string& ) " + ss << endl;
}
void outputString(const string ss) {
cout << "outputString(const string ) " + ss << endl;
}
int main(void) {
//! outputString("ambigiousmethod");
const string constStr = "ambigiousmethod2";
//! outputString(constStr);
} ///:~
How to make distinct call?
EDIT: This piece of code could be compiled with g++ and MSVC.
thanks.
C++ does not allow you to overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object. So something like:
void foo(int);
and
void foo(int&);
is not allowed.
You need to change the number and/or the type of the parameter.
In your case the function that accepts a reference, you can make it accept a pointer, if you want to allow the function to change its argument.
You could change the signature of one of the methods. It may not look pretty, however it is the simplest way.
So you could in principle have
void outputString(const string &ss, int notneeded) {
cout << "outputString(const string& ) " + ss << endl;
}
void outputString(const string ss) {
cout << "outputString(const string ) " + ss << endl;
}
and when you want to call the first function just call it with:
outputString("ambigiousmethod", 0);
which will result in a distinguishing call.
There is no other way (I'd love to be proven wrong on this one) since C++ does not allow overloading where passing (by value or by reference) is the only difference in signature.
Edit: as pointed out by bzabhi, you could also change the signature by changing the reference to a pointer. In the example you gave that would work, however you may have to change function code on some occasions.
According to your code, u need only
void outputString(const string &ss).
Because both methods cannot change the argument to the caller (because it's const reference or by-value passing).
Why do you need those 2 methods?
I recommend using the techinque of giving each and every function a unique name., i.e., do not use syntax overloading. I have been using it for years and I've only found advantages in it.