Method that takes in integers or strings. C++ - c++

So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.
For instance
the method (called up):
//goes to coordinates 5,6 (creates side of 5 with a char called 'X')
triangle(5,6,5,'X',"",5);
Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type
triangle(5,6,5,'X',"I love code", );
But an error would pop up and say that it needs one more parameter.
I've done some searching on boolean methods, like in java when you can type
public static void randommethod bool(/*params*\){
/*Enter code if its either true or false*/
}
But I've come up empty with any trying to find a method like that in C++.

Judging by the title you probably want to be able to pass either int or string which will be printed as message. You can template your triangle function to accept anything:
#include <iostream>
template <typename T>
void triangle(int x, int y, int z, char c, T anything)
{
std::cout << anything << std::endl;
}
int main()
{
triangle(5, 6, 5, 'X', "I love code");
triangle(5, 6, 5, 'X', 5);
return 0;
}
Will print:
I love code
5

As others have said, you can implement function overloading to achieve your desired behavior. Take a look at C++ Overloading to fully understand. Here is a brief example.
#include <iostream>
#include <string>
class Shapes
{
public:
void triangle(int x,
int y,
int z,
char unit,
std::string & text,
int optional)
{
std::cout << "triangle with optional parameters" << std::endl;
}
void triangle(int x,
int y,
int z,
char unit,
std::string & text)
{
std::cout << "triangle with minimal parameters" << std::endl;
}
};

I'm not really sure what each parameter corresponds to in your function, but if you want the last parameter to be optional, then you need to explicitly make it an optional parameter. When you create the function definition/prototype, you just assign the optional parameter the default value. If no value is provided, the default value is used.
For example, if I have a function to draw a triangle, I could write:
public void triangle(int base, int side1, int side2=1)
{
....
}
The side2 variable is optional. If no value is provided, 1 becomes the value. You could give the optional variable some kind of nonsense value that the function will detect and perform actions accordingly. Just make sure that the optional parameter is last in the list of parameters, otherwise it will give errors.
Hope this helps.

Related

C++ Member Function That Returns A Value of Two other member functions

I had this question on a test about a month ago and I still can't seem to understand it completely and quite frankly it's driving me crazy. I will include the question at the bottom. But, it's asking to create a single parameter constructor that creates a new "Vector" (the name of the class) which is the sum of two others. The vector class I made has a function set/get x and set/get y. My hang up is I can't seem to figure out how to make a function that adds the two x's and y's together from vector and vector1 to create a new Vector...call it vector2. I'll include everything I got so far. Thanks to anyone willing to make it through the wall of text as confusing as it must be haha.
Write a class Vertor with the following properties and place the class in a separate header file :
Add member function with a single parameter of another vector and returns a new vector that is the sum of the two (to add vectors you sum the components, for example, Cx = Ax + Bx and Cy = Ay + By).
Write a program that includes the Vector header file, constructs two different vectors and demonstrates the magnitude, angle, and add functions.
Data Members
vector
x component
y component
Member Functions
Set and Get functions for all data members
Magnitude member function
Angle member function (angle = inverse tangent(y / x))
ps I hope I am not doing anything wrong by uploading this and asking I have waited this entire time because I didn't want to break some sort of rule in the community....that I am honestly desperate to become a part of. I've dreamed of doing this my whole life and finally....ahh i digress sorry thanks guys
Oh...my code
#include "Vertor.h"
#include <iostream>
int main()
{
// creates a vector class
Vector vector;
vector.setXcom(4); // sets X
vector.setYcom(12); // sets Y
Vector vector1; // Creates another vector
vector1.setXcom(3);
vector1.setYcom(52);
Vector vector2; // constructs another vector that returns the sum of two other vectors
cout << vector.getXcom() << endl;
cout << vector.getYcom() << endl;
cout << vector.getMag() << endl;
cout << vector.getAng() << endl;
cout << vector1.getXcom() << endl;
cout << vector1.getYcom() << endl;
cout << vector1.getMag() << endl;
cout << vector1.getAng() << endl;
}
#include<iostream>
using namespace std;
// initalize variables
double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
{
public:
void setXcom(double x) // setX function
{
xcomponent = x;
}
void setYcom(double y) // setY function
{
ycomponent = y;
}
double getXcom() // getX function
{
return xcomponent;
}
double getYcom() // getY function
{
return ycomponent;
}
double getMag() // get magnitude function
{
double ans = sqrt((xcomponent * xcomponent) + (ycomponent * ycomponent));
return ans;
}
double getAng() // get angle function
{
double annns = atan(xcomponent / ycomponent);
return annns;
}
// setnewvec function to make a new vector from two others
void setNewVec(int a, int b)
{
xcomponent = a;
ycomponent = b;
}
// NOT SURE
Vector getNewVec(int a, int b)
{
return a + a;
return b + b;
}
};
So you have an absolutely fundamental misunderstanding or gap in your knowledge about how objects work, and this task will be impossible until you sort that out.
To illustrate here's a simpler example written in the style of your code above. I'll follow that with the same example written as it should be. This example is a simple Person class which has an age 'component'.
int age;
class Person
{
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
int main()
{
Person fred;
fred.setAge(22);
Person mary;
mary.setAge(33);
cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}
If you run this program the output will be Fred is 33 and Mary is 33. Both the people have the same age even though you set them as different in the program.
The problem is that although this program has two people it only has one age. So it's literally impossible for the two people to have different ages.
Here's the program written correctly. The crucial difference is that the age variable is inside the class. This means that each Person object gets it's own age.
class Person
{
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
private:
int age;
};
int main()
{
Person fred;
fred.setAge(22);
Person mary;
mary.setAge(33);
cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}
Now the output is Fred is 22 and Mary is 33 as it should be.
First thing you need to do, is to move xcomponent and ycomponent to inside the object. Right now they are global variables which means they share values in all objects you create (and outside object too).
I'm gonna assume you've learned about structures before moving to objects. It's pretty hard to understand object without knowing structures first.
Structures and classes are very similar. They both are containers for variables. Classes are a little more advanced version that usually hides the raw data and instead provides member functions (sometimes called methods) that allow to manipulate the data inside in a more convenient way.
Anyway, when you create a new object of a class, you create it with a new copy all member variables (fields) inside. This way, they can have different values for each object.
Your code is pretty easy to fix in that regard. Just move definition of these variables inside your class.
Old code:
double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
{
public:
//...
};
New code:
class Vector // creates Vector class
{
double xcomponent, ycomponent;
double ans, anns, annns;
public:
//...
};
Now we can work on the return value.
Your return value of getNewVec is all right. You've declared that you want to return an object of type Vector and this is exactly what you want.
However, the function should also take a single vector as an argument. Right now you have tho arguments int a and int b, none of which is a Vector. We need to change that to Vector otherVector to do what your assignment said.
The call of the function looks like this: someVector.getNewVec(someOtherVector).
When it runs, you have two vectors accessible inside of it. The first of them is the one on which the function was called. You have direct access to its fields. The second one is of course the argument otherVector. You can access its fields through its member functions. (Or you can access directly its private fields because you're in a member function of its class.)
Now you need to construct the new vector.
The simplest way is to just create it and assign the values one by one:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(xcomponent + otherVector.getXcom());
newVector.setYcom(ycomponent + otherVector.getYcom());
return newVector;
}
or:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(xcomponent + otherVector.xcomponent);
newVector.setYcom(ycomponent + otherVector.ycomponent);
return newVector;
}
or if you really want:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(this->getXcom() + otherVector.getXcom());
newVector.setYcom(this->getYcom() + otherVector.getYcom());
return newVector;
}
(this is a pointer the object your inside of. You have access to it from each member function.)
I recommend the second option.
Some additional stuff you can read about if your interested...
(I'm not gonna go into any details here.)
Constructors
You can have a special member function that is called when object it's created that is supposed to set initial values to the fields.
It is written similar to a function, except is doesn't have a return value and it's name is always the same as the name of the class.
Vector(int x, int y)
{
xcomponent = x;
ycomponent = y;
}
That allows to create an abject and assign the values in one line so instead of:
Vector newVector;
newVector.setXcom(12);
newVector.setYcom(42);
you can have:
Vector newVector(12, 42);
You can have more than one constructor with different list of arguments.
You can create an operator instead of a normal function. An operator is a function with specific name and arguments that can be called similarly to built-in mathematical operations.
Operator for addition looks like this:
Vector operator+(Vector otherVector)
//the body is the same as getNewVec
You could call it like a normal member function:
someVector.operator+(someOtherVector)
but a better way of writing it is:
someVector + someOtherVector

Best way to send multiple arguments of different types to a method for processing. c++

Currently I have a method that works as follows:
std::stringstream ss; ss << "lives:" << this->Lives;
Text->RenderText(ss.str(), font, x, y, scale,color);
Now this seems messy to me and I wanted to reduce it down to one line.
But I cant seem to think of a way to do it cleanly.
I thought of using varidic functions, but that restricts me to one type and I have to specify the number of arguments.
Also though of using a std::initializer_list or varidic templates but it doesn't seem any nicer.
In this solution: Here An answer provided by Georg Fritzsche showed a posible solution using:
helper() << a << b << c;
But the actual implementation of it I'm.... not sure of.
Something akin to:
Text->render(font, x, y, scale,color) << "lives:" << this->Lives;
would be nice, but in the method I'm not sure how to define it.
I cant return a stringstream object, because I cant access it after the return.
So how does a method like this with chaining << work?
Return a temporary object that accumulates all the parts of your string, then when it is automatically destroyed at the end of the statement, have it render the content in its destructor.
#include <utility>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
class Renderer {
stringstream sstream;
float x;
float y;
public:
Renderer(float x, float y) : x(x), y(y){}
template<class T>
Renderer && operator<<(T&& t) {
sstream << std::forward<T>(t);
return std::move(*this);
};
~Renderer() {
// your real code replaces the line below..
cout << sstream.str() << endl;
}
};
Renderer render(float x, float y) {
return Renderer(x, y);
}
int main() {
int i = 5;
render() << "foo" << i;
}
live: https://wandbox.org/permlink/UToweQELJ4jt0QYl
How I'd deal with this
Okay, so you have this:
std::stringstream ss; ss << "lives:" << this->Lives;
Text->RenderText(ss.str(), font, x, y, scale,color);
Now if you really want to do it in a single line, why not put the string generation into a single function call, something specific like
std::string life_text(int lifecount){
std::stringstream ss;
ss<<"lives:"<<lifecount;
return ss.str();
}
So you can call render like this:
Text->render(life_text(lives), x, y, scale,color);
What you're looking for
First, before I answer the question that you asked, the << operator does not imply method chaining. At least not in vanilla C++, in fact, I don't think it's used anywhere like that in c++.
The stream objects aren't really chaining a method, but calling something like
template<typename T> std::stringstream& operator<<(std::stringstream& rightside,T leftside){
rightside.append(leftside);
return rightside;
}
So what happens at each step of that is something like:
stringstream r;
r<<"lives:";
r<<this->lives;
What you are asking for isn't really all that simple. You would need to change the rendertext function to return a new sort of object that you can pass arguments to. That's hard.
Second of all, that would mean that your evaluation order would make this somewhat more challenging. There are ways around that, but I don't know if this is a situation where a simple convenience function like above wouldn't be better.
If you're dead set on doing this that way, then you might have to do something that is really potentially very problematic. You'd have to make the object call the actual render function(which I assume you probably have from some framework) at its disposal.
Fine, but now you've required adding some scope that might matter if you need this done in a specific order. It would look, potentially, like this:
{
Text->render(x,y,scale,color)<<"lives:"<<this->Lives;
}
To my eyes, that looks frustrating.
I'll answer any questions you might have relating to my answer, if you'd like, but, at least to my eyes, your original goal seems like you're barking up the wrong tree with how you'd like to do this.
Something approaching a solution in the manner you wanted
template<std::function<typename ReturnType(std::string&,typename Ts...)> Func>
class caller{
std::stringstream r;
Ts... arguments;
Func storedFunction;
public:
caller(Func x,typename Ts...):storedFunction(x){
arguments=Ts;
}
~caller(){
Func(r.str(),...Ts);
}
friend template<typename S,typename P> caller<S>& operator<<(caller<S>&,T value);
};
template<typename S,typename P> caller<S>& operator<<(caller<S>& c, T value){
c.r<<value;
}
caller a_suitable_name(std::bind(&Text::Render,&Text),_those_other_arguments);
caller<<"lives:"<
This isn't likely to work in its present form, but I don't have time to finish the definition.

C++ function about usage of return

Hello i am totally new to c++ programming, I had a question when we use a int function why do we have to use return command like we can use cout << sum << endl; and call the function in main(). but for return we have to do like cout << printSum();
Case 1:
#include <iostream>
using namespace std;
int addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
return 0;
}// without using return
Case 2:
#include <iostream>
using namespace std;
int addNumbers(int x, int y){
int sum = x + y;
return sum;
}
int main() {
cout << addNumbers(4, 5) << endl;
return 0;
}// return method
return statement is seemingly very basic, but in fact, one of the most puzzling aspects of procedural programming for freshman students in our local university.
What are the functions anyway?
Functions are the building blocks of procedural and functional programming languages. You might think of a function as of reusable, maintainable block of code responsible for some action. If you perform some operations often together, you might want to "pack" them inside a function. A "good" function is a little machine that takes some input data and gives back processed data.
In C++ you can "share" the results of the processing with "outside code" by returning a value, modifying a parameter (worse) or modifying the global state (worst).
In simple case, "returning" functions are direct analogs of math functions like y = f(x) (even the call syntax is very similar). As a programmer you just define what is x, what is y and how exactly f maps x to y.
Printing vs returning
Now, the printing into console (terminal) and returning are not the same. In simple words, printing is just showing the user some characters on the screen ("speaking with user"). Returning from function allows to receive the result from function ("speaking with outside code"), but it's invisible for the user unless you print it afterwards .
Different function layouts you may encounter while learning
(does not pretend to be an exhaustive list)
So, in your class or tutorial sometimes they teach you how to
(1) print an object directly within main()
int main() {
int i = 42 + 13;
std::cout << i << std::endl;
}
(2) print an object inside a function
void printSum(int a, int b) {
int i = a + b;
std::cout << i << std::endl;
}
int main() {
printSum(42, 13);
}
(3) return an object from the function and printing afterward
void sum(int a, int b) {
return a + b;
}
int main() {
int s = sum(42, 13);
std::cout << s << std::endl;
}
Obviously, (1) is not reusable at all: to change parameters you must intervene into the program logic. Also, if logic is something more than just a sum, main() function will grow quickly in size and become unmaintainable. Responsibilities will be scattered across the code, violating Single responsibility principle
(2) is better in all aspects: function encapsulates logic in a separate place in code, has distinctive name, can be changed separately from main function. Function can be called with different values, and changing arguments doesn't change the function.
But it still has 2 responsibilities: perform the calculation and output to the screen. What if you want not to print the result, but write it to a file? or send it via network? or just discard it? You will need to write another function. The logic inside this new function will be the same, thus introducing duplication and violating DRY principle. Also, (2) is not a pure function because it is modifying std::cout which is basically the global state (we say that this function has "side effects").
Also, you can think about (2) as if it was (1), but with whole program logic moved from main() into a separate function (that's why sometimes functions are called "subprograms").
(3) solves the multiple responsibility problem, by getting rid of printing (moving it into the "user code"). The function contains only pure logic. Now it's a number crunching machine. In main function you can decide what to do with the result of the calculations without touching the calculating function. It becomes a "black box". No need to worry how it is implemented, and no need to change anything, it just works.
In your post there is a shorter version of (3):
int main() {
std::cout << sum(42, 13) << std::endl;
}
The difference is that no temporary object int s being created, but return value is being written directly to std::cout (in fact, passed as a parameter to a function called operator<<)
In real life
In real-life programming, most of the time you will be writing functions like (3), that don't print anything. Printing to terminal is just a quick and simple way to visualize data. That's why you've been taught how to output to standard streams rather than writing to the files, network sockets or showing GUI widgets. Console printing is also very handy during debugging.
See also:
Call Stack - Wikipedia to better understand how function calls happen under the hood
The Definitive C++ Book Guide and List might be of help too.
P.S. There is a big deal of simplification in this post, thus the usage of lots of quoted terms.
The int function must return an int. If you don't want to return values, you can use a void function:
#include <iostream>
using namespace std;
void addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
return 0;
}
The main() must return int (standard), which means that the program ran successfully (0). You can even leave the return statement out of main(), but it will return zero (implicit).
#include <iostream>
using namespace std;
void addNumbers(int x, int y){
int sum = x + y;
cout << sum << endl;
}
int main() {
addNumbers(4, 5);
}
You have two slightly different scenario in both of your snippets.
Case 1: You are printing the value from the called function, before the function finishes execution. So, you don't (need to) return any value. So you don't need a return statement.
Case 2: You are expecting the function to return the value which will get printd. So, you need to have a the return in your called function.
This is because of the return types of the function. Some times you want a function to give you a result instead of just doing things with the information you put into it.
Just like a variable has a type such as int and string, a function wants a type for the item it will be returning.
Here is a website which might help you get into the basics of functions including information about return types.

why does "ClassType Object;" equals to "ClassType(Object);" in C++?

in first, want to start to mention that it could be sorry for my bad english.
in C++, when we want to create a instance of certain type of class, we usually use "ClassType ObjectName;"
for example,
class Foo {};
Foo instance1;
but, i've met some codes make me embarassment a little. it following next.
class A {/*....bla bla*/};
class B {
public:
B(char*) {}
};
void main() {
A aaa;
B(aaa); // this makes a error.
}
by trial and error, i could know that "B(aaa);" is exactly same to "B aaa;".
But why? is this a kind of what depicted on standard documents? if so, please let me know where i can see.
Thanks in advance.
UPDATE:
Thank you for your all replies.
But i think that i've omitted some codes. Sorry.
#include <iostream>
using namespace std;
class A
{
};
class B
{
public:
B() { cout << "null\n"; }
B(char* str) {}
void print() {
cout << "print!\n";
}
};
void main()
{
A aaa;
//B(aaa); this line makes a error that says 'redefinition; different basic types'. VS2008
B(aa1);
aa1.print();
}
Output:
null
print!
as you can see, "B(aa1)" statement means not to pass aa1 to constructor as argument, but to create a instance aa1.
Until now, I've known "B(argument)" to "Pass argument to propel one of a overloaded construtor, and create a nameless temporary instance".
but value "aa1" looks lke neither a defined value nor a temporary instance.
Sometimes a set of parenthesis is needed to disambiguate declarations.
For example:
int *f(); // a function returning a pointer to int
int (*f)(); // a pointer to a function returning an int
Rather than listing exactly when and where using parenthesis is required and where it perhaps should be forbidden (because it is useless), the standard just says that they are allowed.
So you end up with the slightly confusing:
int a; // an int variable
int (b); // another int variable

how does the structure dereference operator work?

I am a java programmer trying to teach myself c++. Please cut me a little slack if I ask simple questions at first.
I would like to understand how the structure dereference operator works. Specifically, can anyone tell me what the following line of code does in explicit terms?
if (elements[i]->test(arga, argb)) {}
test(arga,argb) is a Boolean function in the same class, and elements is a vector of instances of the element class. Here is the code that immediately surrounds the line above, about which I am interested:
for (unsigned i = 0; i < elements.size(); ++i) {
T arga = INFINITY, argb = INFINITY;
//using namespace std;
//std::cout >> elements[i] >> std::endl;
//std::cout >> test(arga, argb) >> std::endl;
if (elements[i]->test(arga, argb)) {
//some code
}
}
It seems that the if line is testing to see whether or not the boolean returned by test(arga,argb) is part of the given instance of the elements class. But when I try to expose the underlying values of elements[i] or test(arga,argb) with the cout lines above, the compiler throws errors until I comment those lines out. In java, I would be able to fiddle around with this until I found values of each that correspond with each other, and then I would understand the line of code. But I do not know how to figure out what this line of code does in C++. Can anyone give me a clear explanation, preferably supported by a link or two to some references online?
elements[i]->test (arga, argb)
If we break down the statement, reading from left-to-right, we will end up with the below:
access the ith element in an array (or array-like) entity named elements
the element accessed (elements[i]) is a pointer to an object
call the member-function named test on elements[i] and pass it two arguments; arga and argb
if we disregard the fact that you wrote std::cout >> instead of std::cout << (the latter is the correct form), we end up with two reasons for your described errors:
your compiler complains about std::cout << element[i] because no suitable overload is found to handle an entity of the type of element[i] and an std::ostream& (which is the underlying type of std::cout).
your compiler complains about std::cout << test (arga, argb) because there is no function in scope named test that takes two arguments corresponding to arga, argv. test, in your snippet, is a member-function that belongs to an entity, it's not callable by its own.
Welcome to C++.
First, the syntax for output is:
cout<<
instead of
cout>>
You are right in guessing that test is a function that returns boolean.Here elements[i] is a pointer pointing to a struct element which has this test function.
To learn C++, you can use these articles that I wrote.Good luck!
Since numerous respondents told me that I need to provide the code before they can answer, I looked deeper in the code, and re-wrote something which tells me that the line:
if (elements[i]->test(arga, argb)) {}
is a test to see whether or not the boolean member function of elements[i] is true.
The c++ program that I wrote to identify the meaning of -> in this context is:
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
template<typename T>
class Bone
{
public:
std::string myName;
int mySize;
Bone(const std::string &name, const int &size) : myName(name), mySize(size)
{}
bool isBigger(const int &testSize) const
{
if (testSize > mySize) return false;
else return true;
}
};
int main(int argc, char **argv)
{
std::vector<Bone<float> *> bones;
// name, location, size
bones.push_back(new Bone<float>("femur", 10));
bones.push_back(new Bone<float>("ulna", 4));
bones.push_back(new Bone<float>("maxilla", 3));
int testSize = 6;
// test each bone to see if it is bigger than testSize
for (unsigned i = 0; i < bones.size(); ++i) {
if (bones[i]->isBigger(testSize)) {
std::cout << bones[i]->myName; std::cout << " is bigger than testSize! " << std::endl;
}
}
while (!bones.empty()) {
Bone<float> *thisBone = bones.back();
bones.pop_back();
delete thisBone;
}
return 0;
}
Thank you to everyone who led me to figure this out.