Use of parametrised constructor is giving error - c++

I've been trying to learn about parametrised constructors:
Here is the program I wrote:
#include <iostream> //Using a parametrised constructor i.e. we give an integer value as a parameter
using namespace std;
class item{
int cost;
int price;
public:
item (int a){
cost=a;
}
void display(){ //Display is not a constructor, hence we need to specify its return type and parameters
cout << cost;
}
} item1;
int main(){
item1(5);
item1.display();
return 0;
}
However, I get an error on Visual Studio Code:
call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
Can anyone tell me what's wrong with the code?

At the end of class creation you are asking to create an object named item1 but you are not providing any value, that's why it is throwing error you cannot create an object without '('.
After object creation you can't call the constructor. you can access all the methods and fields.
#include <iostream> //Using a parametrised constructor i.e. we give an integer value as a parameter
using namespace std;
class item{
int cost;
int price;
public:
item (int a){
cost=a;
}
void display(){ //Display is not a constructor, hence we need to specify its return type and parameters
cout << cost;
}
} item1(5);
int main(){
item1.display();
return 0;
}

Related

Why am I getting an "error: declaration of 'Coin::Coin()' outside of class is not definition" message?

I am just learning about classes in C++, and I am trying to create this Coin class that simulates a coin flip with a method called toss() that will return either 0 or 1 which represent heads or tails respectively.
#include <iostream>
#include <cstdlib>
using namespace std;
class Coin {
private:
public:
Coin();
int toss();
};
Coin::Coin();
int Coin::toss() {
int num;
num = rand() % 2;
return num;
}
int main() {
Coin C;
cout << C.toss() << endl;
}
I keep getting an error that says: error: declaration of 'Coin::Coin()' outside of class is not definition. I am assuming that I did not declare my constructor correctly, but I am not sure.
The problem is that you're trying to declare the constructor outside the class when you wrote Coin::Coin();.
To solve this replace Coin::Coin(); with Coin::Coin(){} as shown below:
class Coin {
private:
public:
Coin();
int toss();
};
//----------v--->semicolon removed from here
Coin::Coin() //this is a definition now
{
}

Classes: Instantiating Object Confusion

Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}

Why can I use the constructor without an object declaration?

Why can I use the constructor without a previous object declaration? And, if the previous works, why do I get an error when using k()?
Here is my code:
#include <iostream>
using namespace std;
class Test
{
int i, x;
public:
Test(int ii = 0)
{
cout<<"WOW!";
cout<<i<<" ";
i=ii;
}
void k()
{
cout<<i<<" ";
}
};
int main()
{
Test();
k(); ///k was not declared in this scope
return 0;
}
Why can I use the constructor without a previous object declaration?
A constructor is used to create a new object. So it can't be called on a previous object.
And, if the previous works, why do I get an error when using k()?
Because k() is a non-static method of Test, so it needs a Test object to call it on. You can't call it as a standalone function.
int main()
{
Test t;
t.k();
return 0;
}
You can create instance of the class because the name of the class can be found with name lookup from the current (the global in this case) namespace, and the class has been defined.
You haven't declared a free function by the name k, so you cannot call such function.

How to create an object with the constructor with parameter

For some reason whenever I try running my code it always call the default constructor but it should be calling the constructor with parameters.
#include "pokemon.h"
int main()
{
int choice;
cout<<"input 1 2 or 3"<<endl;
cin>>choice;
if(choice==1||choice==2||choice==3)
{
pokemon(choice);
}
}
in my headerfile i have
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
class pokemon{
public:
pokemon();//default constructor
pokemon(int a);
~pokemon();//desconstructor
pokemon(const pokemon& c);
void train();
void feed();
bool isnothappy();
string getName();//accessor for the name
int getPowerlevel();//accessor for the power level
string getColor();//accessor for the color
string getType();//accessor
int getHappylevel();//accessor
static int getNumObjects();
void set_type(string);//mutator
void set_color(string);//mutator
void set_power_level(int);//mutator
void set_happy_level(int);//mutator
void set_name(string);//mutator
private:
string name;
string color;
string type;
int power_level;
int happy_level;
static int numberobject;
};
and in my other .cpp file i have
int pokemon::numberobject=0;//initialize static member variable
pokemon::pokemon(){//default constructor
name="pikachu";
color="yellow";
type="electric";
power_level=0;
happy_level=1;
cout<<"The default constructor is being called"<<endl;
++numberobject;
}
pokemon::pokemon(int a)
{
if(a==0)
{
name="Pikachu";
color="yellow";
type="electric";
power_level=1;
happy_level=1;
}
else if(a==1)
{
name="Bulbasaur";
color="green";
type="grass";
power_level=1;
happy_level=1;
}
else if(a==2)
{
name="Charmander";
color="red";
type="fire";
power_level=1;
happy_level=1;
}
else if(a==3)
{
name="Squritle";
color="blue";
type="water";
power_level=1;
happy_level=1;
}
cout<<"Congratulations you have chosen "<<getName()<<". This " <<getColor()<<" "<<getType()<<" pokemon is really quite energetic!"<<endl;
++numberobject;
}
pokemon::~pokemon()
{
//cout<<"the destructor is now being called"<<endl;
//cout<<"the number of objects before the destructor is "<<pokemon::getNumObjects()<<endl;
--numberobject;
cout<<"Now you have a total number of "<<pokemon::getNumObjects()<<endl;
}
pokemon::pokemon(const pokemon& c)//copy constructor
{
name=c.name;
color=c.color;
type=c.type;
power_level=c.power_level;
happy_level=c.happy_level;
++numberobject;
}
I have both my constructors declared and defined in my other files but this darn thing always calls the default constructor
This code:
pokemon(choice);
means the same as:
pokemon choice;
It declares a variable called choice of type pokemon, and there are no arguments given to the constructor. (You're allowed to put extra parentheses in declarations in some places).
If you meant to declare a variable where choice is a constructor argument then you have to write:
pokemon foo(choice);
If you meant to create a temporary object (which will be immediately destroyed) with choice as argument, you can write (pokemon)choice;, or pokemon(+choice);, or since C++11, pokemon{choice};.
This issue with ambiguity between declarations and non-declarations can arise any time a statement begins with a type-name followed by (. The rule is that if it is syntactically correct for a declaration then it is treated as a declaration. See most-vexing-parse for other such cases.

C++ Need help using custom constructor

new to c++ and cant figure out why visual studio doesn't like my "HealthProfile person.setFirstName(first)" line of code. The error is with "person" and the error is no default constructor. It's probably something painfully obvious, but my code is almost identical from the code in my book. Thanks in advance!
main:
#include <iostream>
#include "HealthProfile.h"
using namespace std;
int main()
{
string first;
HealthProfile person;
cout << "Enter first name" << endl;
getline(cin,first);
person.setFirstName(first);
}
header:
#include <string>
using namespace std;
class HealthProfile
{
public:
HealthProfile(string, string, string, int, int, int, int, int);
void setFirstName(string);
string getFirstName();
void setLastName(string);
string getLastName();
};
function:
#include <iostream>
#include "HealthProfile.h"
using namespace std;
HealthProfile::HealthProfile(string first, string last, string g,
int m, int d, int y, int h, int w)
{
setFirstName(first);
setLastName(last);
setGender(g);
setMonth(m);
setDay(d);
setYear(y);
setHeight(h);
setWeight(w);
}
void HealthProfile::setFirstName(string first)
{
firstName = first;
}
string HealthProfile::getFirstName()
{
return firstName;
}
void HealthProfile::setLastName(string last)
{
lastName = last;
}
string HealthProfile::getLastName()
{
return lastName;
}
There is nothing wrong with setFirstName().
The issue is that you've declared a constructor that takes three strings and five ints, this removes the default constructor which you are using when you call HealthProfile person
The solution is to either use the HealthProfile cosntructor and pass it three strings and five ints, or to declare and define a constructor that takes no parameters by adding HealthProfile(){} to the header.
This line in main:
HealthProfile person;
Declares an instance of the HealthProfile class using a default constructor. You've not declared a default constructor. Creating your own custom constructor prevents a default constructor from being implicitly created for you. If you want to use a default constructor as well as a custom one, you need to explicitly declare and define it. If you don't want to use a default constructor, then pass in arguments to use your custom one.
To declare a default constructor in your .h:
HealthProfile();
And to define it in your .cpp:
HealthProfile::HealthProfile() { }
Or to simply call your existing custom constructor in main:
HealthProfile person(first,last,g,m,d,y,h,w); // AFTER collecting values for these arguments