Constructor error anytime I use private variables in VS Code - c++

We're learning about constructors in class and I was trying to experiment with an overloaded constructor. When I run my program I keep getting an error written in the color red that says...
~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
^This only happens when I try to use private variables, when everything is public nothing goes wrong.
///Here's my code
#include <iostream>
using namespace std;
class JCole {
private:
string song;
string album;
int albumNum;
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
int main() {
JCole album1("Punchin the clock", "The Off-Season", 6);
JCole album2("ATM","KOD",5);
cout << album1.song << " " << album1.album << " " << album1.albumNum << endl;
cout << album2.song << " " << album2.album << " " << album2.albumNum << endl;
return 0;
}

Your constructor is declared as private because you haven't changed the access setting.
Try this:
class JCole {
private:
string song;
string album;
int albumNum;
// Insert:
public:
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
A private constructor is a nasty thing; only members of the class can call it. Thus wreaking havoc with external code that wants to instantiate this class.
Also, you can use many public:, private:, protected: within your class and in any order.

Related

trying to get different outputs from polymorphic function

Hi StackOverflow community!
I'm expecting different outputs depending on the class of object to be printed but that's not the case.
Medium.h
#include "Datum.h"
#include "Person.h"
class Medium
{
public:
Medium(std::string initTitel);
virtual ~Medium(void);
void ausgabe() const;
bool ausleihen(Person person, Datum ausleihdatum);
void zurueckgeben();
unsigned int getID();
protected:
static unsigned int currentID;
unsigned int ID;
std::string titel;
bool status;
Datum datumAusgeliehen;
Person personAusgeliehen;
};
Medium.cpp
#include "Medium.h"
#include <string>
#include <iostream>
unsigned int Medium::currentID = 1;
Medium::Medium(std::string initTitel): titel(initTitel), status(false)
{
ID = currentID++;
}
Medium::~Medium(void) {}
void Medium::ausgabe() const
{
std::cout << "ID: " << ID << std::endl;
std::cout << "Titel: " << titel << std::endl;
switch (status)
{
case true:
std::cout << "Status : Das Medium ist seit dem "
<< datumAusgeliehen << " an "
<< personAusgeliehen.getName() << " ausgeliehen."
<< std::endl;
break;
case false:
std::cout << "Status: Medium ist zurzeit nicht verliehen." << std::endl;
break;
}
}
The function prints ID, title and status to console.
Now depending on the type of Medium, I would like to print extra information using the function void ausgabe() const.
Example: If the Medium is a book(in german buch = book), information about author should be printed, in addition to other information available in Medium class. i.e, I have got the subclass called Buch which also has an void ausgabe() const function, which should print this extra information in class Buch.
Buch.h
#include "Medium.h"
class Buch: public Medium
{
public:
Buch();
Buch(std::string initTitel, std::string initAutor);
virtual ~Buch();
void ausgabe() const;
private:
std::string autor;
};
Buch.cpp
#include "Buch.h"
Buch::Buch(std::string initTitel, std::string initAutor): Medium(initTitel), autor(initAutor)
{ // TODO Auto-generated constructor stub }
Buch::~Buch() { // TODO Auto-generated destructor stub }
void Buch::ausgabe() const
{
Medium::ausgabe();
std::cout << "Autor: " << autor << std::endl;
}
As far as I have: In the class Buch, while calling the output function ausgabe() the extra information autor will be printed automatically. But for the remaining informations from Medium class, could you help. Thanks for your help :)
Now depending on the type of Medium to be printed, I would like to add
extra information to be printed. E.g. if the Medium is a book,
information about author should be printed too.
So you are looking for dynamic-polymorphism. Then, you need to make void ausgabe()const function to virtual in your base class(Medium), in order to call it polymorphically. And you need to override it in other subclasses(for instance class Buch). In the given code anyways these are not there. In addition to that, you also need virtual destructor at your base class.
Then in your class Buch's ausgabe() should be:
void ausgabe()const override
{
Medium::ausgabe(); // call first base class's ausgabe()
std::cout << "autor :" << autor << std::endl;
}
Then in your main, you can do this: See an example code here
int main ()
{
std::unique_ptr<Medium> some_objects[2];
some_objects[0] = std::make_unique<Medium>("Some Title");
some_objects[1] = std::make_unique<Buch>("Title 2", "user9775960");
for(auto& obj_type: some_objects)
obj_type->ausgabe();
return 0;
}
PS: always try to post English written code in the community, so that everybody can follow.

Cannot call function of a class from main

#include <iostream>
#include <string>
using namespace std;
// my code starts
class Cat {
public:
int age;
string name, race, voice;
Cat(int age2,string name2,string race2,string voice2);
void PrintInformation();
};
Cat::Cat(int age2,string name2,string race2,string voice2) {
age = age2;
name = name2;
race = race2;
voice = voice2;
}
Cat::Meow(){
cout << "Cat says: " << fluffy.Meow() << endl;
}
void Cat::PrintInformation() {
cout << "Name: " << name;
cout << "\nAge: " << age;
cout << "\nRace: " << race << endl;
}
// my code ends
int main()
{
Cat fluffy(2, "Fluffy", "Bombay", "Meoow!!!");
fluffy.PrintInformation();
cout << "Cat says: " << fluffy.Meow();
}
I can't seem to figure out how to make this code work. My main problems seems to be that i don't know how to call fluffy.Meow(); from int main().
Thanks, for any help!
You forgot to declare Cat::Meow in the class declaration.
//some code
void PrintInformation();
void Meow();
Additionally, you have to specify what the return type of the function Meow is, in your case it would be void, because it returns nothing.
You also have some recursion going on, Meow calling Meow (forgetting about the fact that fluffy isn't a variable in this scope). Your Cat class knows nothing about the instance fluffy, so you can't access it.
I guess you meant voice instead.

C++: Derived classes, "no matching constructor" error

I've been working on this assignment for a while. Here's the instructions:
You are to design an abstract class called Employee whose members are
as given below (make them protected):
Data members: char *name, long int ID
Two constructors: A Default constructor // intitialize data memebrs to
the default values and a copy constructor
Methods: setPerson (char *n, long int id) //allows user to set
information for each person A function called Print () // should be a
virtual function, that prints the data attributes of the class. and a
destructor
Also define two classes that derived from class Employee, called
Manager and Secretary. Each class should inherit all members from the
base class and has its own data members and member functions as well.
The Manager should have a data member called degree for his/her
undergraduate degree (e.g. diploma, bachelor, master, doctor), the
Secretary should have her contract (can be a Boolean value 1/0 for
permanent/temporary).
All member functions of derived class should be overrided from their
base class.
Write the following main() to test your classes
int main() {
Employee * p = new Manager(“Bruce Lee”, 0234567, “Dr.”);
P.print();
Secretary p2;
p2.setPerson(“Wilma Jones”, 0341256, “permanent”);
delete p;
p = & p2;
p.Print();
return 0;
}
This is everything I've come up with so far, but I'm pretty sure it's riddled with mistakes and that my arguments and variable types are all off.
#include <iostream>
using namespace std;
class Employee{
protected:
char *name;
long int ID;
public:
Employee();
Employee(Employee&);
void setPerson(char * n, long int eID) {
name = n;
ID = eID; };
virtual void Print(){
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl; };
};
class Manager: public Employee {
protected:
char *degree;
public:
void setPerson(char * n, long int eID, char * d){
name = n;
ID = eID;
degree = d;
};
void Print() {
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
cout << "Degree: " << degree << endl;
};
};
class Secretary: public Employee {
protected:
bool contract;
public:
void setPerson(char * n, long int eID, string c){
name = n;
ID = eID;
if (c == "permanent") contract = true;
else contract = false;
};
void Print(){
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
cout << "Contract: " << contract << endl;
};
};
int main() {
Employee * P = new Manager("Bruce Lee", 0234567, "Dr.");
P.Print();
Secretary P2;
P2.setPerson("Wilma Jones", 0341256, "permanent");
delete P;
P = & P2;
P.Print();
return 0;
}
I'm getting an error on line 62 (the first line of the main code):
No matching constructor for initialization of Manager
I've tried reading similar questions, but they haven't helped me much. I think the most confusing thing is contract being a bool value and the use of char arguments. Any guidance at all is appreciated.
The error you're getting is pretty straight-forward: you don't have any constructor for Manager (or Employee) that takes a string, integer (?), and string as arguments.
You have declared the constructor employee but not defined it.
Look at the class employee, Under publc you have declared
Employee();
Employee(Employee&);
But you have not defined the function. You need
Employee :: Employee()
{
bla bla bla
}
and another one for the other signature.

set and get the value of different class members in a class

i am very new to c++ programming and i have written a simple class program to display the name and duration of the project.
#include<iostream>
class project
{
public:
std::string name;
int duration;
};
int main ()
{
project thesis; // object creation of type class
thesis.name = "smart camera"; //object accessing the data members of its class
thesis.duration= 6;
std::cout << " the name of the thesis is" << thesis.name << ;
std::cout << " the duration of thesis in months is" << thesis.duration;
return 0;
But now i need to program the same paradigm with get and set member functions of the class. I need to program somewhat like
#include<iostream.h>
class project
{
std::string name;
int duration;
void setName ( int name1 ); // member functions set
void setDuration( string duration1);
};
void project::setName( int name1)
{
name = name1;
}
void project::setDuration( string duration1);
duration=duration1;
}
// main function
int main()
{
project thesis; // object creation of type class
thesis.setName ( "smart camera" );
theis.setDuration(6.0);
//print the name and duration
return 0;
}
I am not sure whether above code logic is correct, can someone please help me how to proceed with it.
Thanks much
You have written some set functions. You now need some get functions.
int project::getName()
{
return name;
}
std::string project::getDuration( )
{
return duration;
}
Since the data is now private you cannot access it from outside the class. But you can use your get functions in your main function.
std::cout << " the name of the thesis is" << thesis.getName() << '\n';
std::cout << " the duration of the thesis is" << thesis.getDuration() << '\n';

Strange behavior for int / counter

I'm trying to add some songs to a vector inside a class. One of the values I'm storing is an int representing the song. It's essentially a counter. The first song I add should have the value 1, the second value two and so forth. But It's getting other strange values like big random numbers (positives and negatives). I can't wrap my head around what I'm doing wrong. This is the code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Jukebox{
public:
void addSong(string artist, string title, string filename) {
song s {++songCounter, artist, title, filename};
Songs.push_back(s);
}
void printSong (int song) {
cout << Songs[song].no << ". ";
cout << Songs[song].artist << " - ";
cout << Songs[song].title << " : ";
cout << Songs[song].filename << endl;
}
private:
struct song {
int no;
string artist;
string title;
string filename;
};
vector<song> Songs;
int songCounter;
};
int main() {
Jukebox jbox;
jbox.addSong("U2", "Magnificent", "U2-Magnificent.mp3");
jbox.addSong("Sting", "Englishman in New York", "Sting-Englishman_in_New_York.mp3");
jbox.addSong("U2", "One", "U2-One.mp3");
jbox.printSong(0);
jbox.printSong(1);
jbox.printSong(2);
return 0;
}
Update
Ok, I'm probably stupid and should read more about classes before trying to implement this. But I think I did read and I still don't get it. This is what my class looks like now (which won't work):
class Jukebox(): songCounter(0)
{
public:
void addSong(string artist, string title, string filename) {
songCounter++;
song s {songCounter, artist, title, filename};
Songs.push_back(s);
}
void printSong (int song) {
cout << Songs[song].no << ". ";
cout << Songs[song].artist << " - ";
cout << Songs[song].title << " : ";
cout << Songs[song].filename << endl;
}
private:
int songCounter;
struct song {
int no;
string artist;
string title;
string filename;
};
vector<song> Songs;
};
Final word
Ok. From the example I've seen of c++ contructor classes I had some kind of wrong impression of how they worked. Now I think I'm getting it a little bit more. But the syntax still seems strange to me. But I try to read more so I really understand it. Here is what I did and to seems to work:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Jukebox {
public:
void addSong(string artist, string title, string filename) {
songCounter++;
song s {songCounter, artist, title, filename};
Songs.push_back(s);
}
void printSong (int song) {
cout << Songs[song].no << ". ";
cout << Songs[song].artist << " - ";
cout << Songs[song].title << " : ";
cout << Songs[song].filename << endl;
}
Jukebox(): songCounter(0) {} // Constructor
private:
int songCounter;
struct song {
int no;
string artist;
string title;
string filename;
};
vector<song> Songs;
};
int main() {
Jukebox jbox;
jbox.addSong("U2", "Magnificent", "U2-Magnificent.mp3");
jbox.addSong("Sting", "Englishman in New York", "Sting-Englishman_in_New_York.mp3");
jbox.addSong("U2", "One", "U2-One.mp3");
jbox.printSong(0);
jbox.printSong(1);
jbox.printSong(2);
return 0;
}
You did not initialize songCounter in your constructor.
Jukebox(): songCounter(0),//....other members
If you do not initialize it, then it may have any random value and that leaves your program in an Undefined State.
Always be careful while using unitialized variables, it often leads to Undefined Behavior and your program is a good example of it.
Also, I am not sure of your design but probably it should be a static member if you want to use it as a counter, which maintains state for all objects of your Song class.
Or
You will have to explicitly set it to a proper value at time of creating a Song object.
Okay its a counter for JukeBox and not Song class so its still okay to be a member.
You didn't initialize the variable songCounter.
Add the following to the class definition of Jukebox:
Jukebox(): songCounter(0) {}
you need a constructor for Jukebox and in that you need to initialise the counter to 0.
I think you should initialize songCounter to be 0. In the public part of the class:
public Jukebox() : songCounter(0) {}
Where do you initialise songCounter? In C++, primitives aren't zero initialised by default. You need to add
: songCounter(0)
to your constructor.