Hi there, im going through the c++ tutorials and learning about classes and constructors but am having little bit of an issue. I think I understand this example well enough but I dont understand how it would work if you want to return an integer and a string character. can you do it form the same constructor? If you start plugging in string for one of the ints it doesent work right. Thanks for any help!
// example: class constructor
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle (int,int);
int area () {return (width*height);}
};
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
You cannot return anything from the constructor. Within the constructor you usually don't do more than initializing the member variable(s) (int width, height;). These member variables can be of any type like a string. You can add member functions (like area ()) in order to deal with this variables.
If you start plugging in string for one of the ints it doesent work right.
hmm I see, so i made my own code and I used the constructor to just initialize the variables. I have a function that is supposed to get the info I initialized with the constructor and allow me to display it, however, it doesent want to work. I am not really sure what I am doing wrong. my error codes say that the operator im using for my function is incorrect, it also tells me that I have unresolved externals because of my "void", I thought my function was not returning anything but rather just displaying the input it got from the initialization of the constructor.
Alright so I added the string class however I am still getting the error message about unresolved externals. my error code says it has something to do with "void" but I dont really get it.
I think you're confusing a class's member function with a free (non-class) function.
void GetBerryInfo (const Berries& B);
You don't need this.
GetBerryInfo(Berryinfo1);
change this to Berryinfo1.GetBerryInfo(Berryinfo1);
The alternative would be to make Berries::GetBerryInfo be a static member function, meaning it doesn't need to be called through an object of that class.
1 2 3 4 5 6 7 8 9
class Berries {
// ...
staticvoid GetBerryInfo(const Berries& B) { ... }
};
// ...
Berries Berryinfo1( "Raspberries", 7);
Berries::GetBerryInfo(Berryinfo1);
if you get more errors, post the exact error message; especially considering you say you don't understand the error. Being able to "translate" compiler errors in a needed skill in C++.