Not able to access members of a Union - c++

I haee this small piece of code in which I'm trying to create a struct Employee. The employee can be either a manager or worker. I'm having trouble accessing members of the unions. Here's my code
#include <iostream>
#include <string>
using namespace std;
struct Employee {
int id;
union Person {
struct Manager {
int level;
} manager;
struct Worker {
string department;
} worker;
} company[3];
};
int main() {
Employee one;
one.id = 101;
one.company[0].manager.level = 3;
Employee two;
two.id = 102;
two.company[1].worker.department = "Sales";
Employee three;
three.id = 103;
three.company[2].worker.department = "Marketing";
}
The error I get is
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with constructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with destructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with copy assignment operator not allowed in union
arraOfUnions.cc:13:5: note: unrestricted unions only available with -std=c++0x or -std=gnu++0x
I'm not sure what I'm doing wrong. Please help
Thanks SO

You cannot have a non-POD object in your union, but you can have a pointer to a non PDO object (therefore string* is valid).
What are POD types in C++?
Pehaps a const char* is enough, if all you need is access to those string literals "Sales" & "Marketing"-

BTW - you data model is completely wrong. You should not be using a union you need to use a class hierarchy.
You need a base class Employee, and a derived class Manager.
struct Employee {
int id;
string department;
};
struct Manager : public Employee
{
int level;
}
and dont use struct use class
and have better naming for members. like m_company or company_
and dont do using namespace std, say std::string etc
class Employee {
int _id;
std::string _department;
};
class Manager : public Employee
{
int _level;
}

Related

Explicitly initalize abstract base class constructor with value determined by parameter of derived class constructor

Within my vehicle base class, I have a private member variable, string type (for type of vehicle, ie car, motorbike, tricycle, etc).
#pragma once
using namespace std;
#include <string>
#include <iostream>
class vehicle {
public:
vehicle(string reg, string make, string model, int age, string type);
virtual ~vehicle() = default;
virtual double costPerDay() = 0;
protected:
int age;
int perDayCostCap(int costPD);
double penceToPounds(int pence);
private:
const string type;
string const reg, make, model;
};
One of the derived classes, bike, has a numberOfWheels variable which is to be passed into its constructor. I want to initialize the base class constructor with type bicycle or tricycle depending on the numberOfWheels.
I can not figure out how to achieve this, seeing as the base class constructor has to be initialized before the function body of the child class.
The following shows what I would like to achieve (though, I know this is not possible):
bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
:engineCC(engineCC), numOfWheels(numOfWheels) {
string tricOrBic = (numOfWheels == 2) ? "bicicle" : "tricicle";
vehicle:reg=reg, make=make, model=model, age=age, type=tricOrBic;
};
Like this?
bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
: vehicle(reg, make, model, age, numOfWheels == 2 ? "bicycle" : "tricycle")
, engineCC(engineCC)
, numOfWheels(numOfWheels)
{
}
This is normal programming, maybe you had some problem I'm not seeing.

C++ Declaring an inherited constructor?

I'm having difficulties in defining a constructor for a class that inherits the properties of another class
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
};
class SeaTransport: public Transportation {
public:
int portNumber;
SeaTransport(int)::Transportation(int,string,string) {
}
};
I'm having issues with line 18 (SeaTransport(int)::Transportation(int,string,string)).
The error I receive occurs at the pont where I declare Transportation.
As seen in the code, a class Transportation is the body class and class SeaTransport inherits the properies of Transportation.
Transportation::Transportation(int, std::string, std::string)
+2 overloads
type name is not allowed
This error occurs at the int
typedef std::__cxx11::basic_string std::string
type name is not allowed
and this final error occurs at both string variables.
It seems you mix together scoping and a constructor initializer list.
The double-colon operator :: is for scope, while a constructor followed by a single colon and a list of initializations is an initializer list.
You must declare the SeaTransport constructor to take all the arguments, including those for the parent class (assuming you want to pass them on to the base constructor):
SeaTransport(int port, int id, string company, string operator);
Then in the definition (implementation) of the constructor you "call" the parent constructor in the constructor initializer list:
SeaTransport(int port, int id, string company, string oper)
: Transport(id, company, oper), // "Call" the parent class constructor
portNumber(port) // Initialize the own members
{
}
As Mr Some Programmer Dude said, you've a Scope problem in your code,
I will try to answer for your second question which is, how to add featured variables on your constructor.
Same as what you did for the port attribute.
You can define before all your Attribute which is boatNumber as int boadNumber = 0 then, you'll overload your
constructor with boatNumber(num) after the initializer operator and int num before the initializer operator.
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
~Transportation(){}
};
class SeaTransport: public Transportation {
public:
int portNumber;
int boatNumber;
SeaTransport(int num, int port, int id, string company, string oper)
:Transportation(id, company, oper), boatNumber(num),portNumber(port) {}
~SeaTransport(){}
};
But, if you want to get things more specific, you can create another class which is derived from SeaTransport
And then you'll define the number of your boat and more other details, if you want.
I'll draw you an instance of it :
class Boat: public SeaTransport {
public:
int boatNumber;
Boat(int bNum,int num, int port, int id, string company, string oper):
SeaTransport( num, port, id, company, oper),boatNumber(bNum){}
~Boat(){}
};

Personalised name in constructor for different subclasses

Instead of "Car" is there a way to set the name variable of each object according to its class, for example "Turbo 01" or "Tank 02" or "Buggy 03", where id contains the amount of vehicles created.
#include <iostream>
#include <string>
#include <sstream>
static int id = 0; //Total Number of cars right now
class Car
{
private:
std::string name;
Car()
{
std::ostringstream tmp;
std::string temp;
tmp << "Car" << ++id;
temp = tmp.str();
}
Car(std::string name){this->name=name; id++;}
};
class Turbo : public Car()
{
Turbo():Car()
{
}
Turbo(std::string name):Car(name);
{
}
};
First, let's make sure that the class Car compiles by providing the two required template arguments std::array : type and size. For example: std::array<int, 10>.
The problem is that Turbo needs a valid constructor for its base type Car before it can do anythin else. There are two ways, for it to work:
Either you design Car so that there is a default consructor (i.e.without parameters)
Or you put the constructor for Car in the initialisezer list of the Turbo.
For your edited question, the problem is that the Car constructor must be visible for the derived class, so either public or protected, but not private. You can also use default parameters to get rid of redundant code.
Here a solution:
class Car
{
private:
static int id; //Total Number of cars right now SO MEK IT a static class member
std::string name;
public: // public or protected so that derived classes can access it
Car(std::string n="Car") // if a name is provided, it will be used, otherwhise it's "Car".
{
std::ostringstream tmp;
std::string temp;
tmp << n << ++id;
name = tmp.str(); // !! corrected
}
};
int Car::id = 0; // initialisation of static class member
class Turbo : public Car
{
public: // !! corrected
Turbo(std::string n="Turbo") :Car(n) // !!
{ }
};

no matching function for call to employee::employee()

I am trying the derived class example from TCPL.
Manager is kind of employee with additional info of level. I kept getting the error:
no matching function for call to employee::employee()
in the constructor of manager::manager()
All members of employee are public and accessible. What is wrong with the manager constructor?
#include <iostream>
#include <string>
using namespace std;
class employee{
public:
enum type {M,E};
type hier;
string id;
employee(string idd):hier(E){id=idd;};
};
class manager: public employee{
public:
int level;
manager(string idd, int lv){hier=employee::M; id=idd;level=lv;};
};
void print(employee *x){
if(x->hier == employee::E){
cout<<"I am employee with id "<<x->id<<endl;
}
else{
cout<<"I am manager with id "<<x->id<<endl;
manager* y=static_cast<manager *>(x);
cout<<"My level is "<<y->level<<endl;
}
}
int main(){
employee t("334");
manager u("223", 2);
print(&t);
print(&u);
}
Second version
The previous version was bad in terms of encapsulation
This is the new version
#include <iostream>
using namespace std;
enum type {M, E};
class employee{
string id;
type hier;
public:
employee(string idd, type hi=E):hier(hi),id(idd){}
string whatid(){return id;}
type whattype(){return hier;}
};
class manager: public employee{
int level;
public:
manager(string idd, int lv):employee(idd,M),level(lv){}
int whatlv(){return level;}
};
Instead of directly accessing the private member of employee and manager, I made members private and use a function to access them.
#include <iostream>
#include <string>
#include "manager_employee.h"
using namespace std;
void print(employee *x){
if(x->whattype() == E){
cout<<"I am employee with id "<<x->whatid()<<endl;
}
else{
cout<<"I am manager with id "<<x->whatid()<<endl;
manager *y=(manager *)x;
// manager* y=static_cast<manager *>(x);
cout<<"My level is "<<y->whatlv()<<endl;
}
}
int main(){
employee t("334", E);
manager u("223", 2);
print(&t);
print(&u);
}
By declaring a constructor in employee, you remove its default constructor; so you can't create one without specifying the ID.
This means that any derived classes will need to provide the ID to the base-class constructor:
manager(string idd, int lv) : employee(idd) {hier=employee::M; level=lv;}
// ^^^^^^^^^^^^^
For consistency, you might like to initialise level in the initialiser list rather than the constructor body; and it might make more sense to initialise hier to the correct value via another parameter in the employee constructor, rather than giving it a default value then overwriting it:
employee(string idd, type hier = E) : hier(hier), id(idd) {}
manager(string idd, int lv) : employee(idd, M), level(lv) {}
If you have any explicit constructor for a class, the default constructor goes out of existence.
So for that reason, when you initialize an object of the derived class, it tries to initialize the base class members as well. And as you have not given a constructor taking no arguments, this error is thrown.
Either define a default constructor for employee or try calling the base class constructor as:
manager(string idd, int lv):employee(idd){//your code}
Manager constructor should call base class ctor in its initialization list:
manager(string idd, int lv) : employee(idd) {hier=employee::M; id=idd;level=lv;}
Also consider using initlization list for other members in your classes.

How to implement Inheritance in C++ and resolve the error "parent class is not accessible base of child class"?

I am new to C++. I like to explore the idea of Inheritance in C++. Whenever I try to compile the following code I get the error:
for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
D:\C Practice Files\Vehicle.cpp: In function `int main()':
D:\C Practice Files\Vehicle.cpp:26: error: `void Vehicle::setStationary_state(bool)' is inaccessible
D:\C Practice Files\Vehicle.cpp:141: error: within this context
D:\C Practice Files\Vehicle.cpp:141: error: `Vehicle' is not an accessible base of `Ship'
Execution terminated
Here is my code:
#include <iostream.h>
#include <conio.h>
using std::string;
class Vehicle{
private:
bool stationary_state;
double max_speed;
double min_speed;
double weight;
double volume;
int expected_life;
string fuel_type;
string model;
string year_of_manufacture;
public:
Vehicle(){
}
void setStationary_state(bool m){
stationary_state = m;
}
bool getStationary_state(){
return stationary_state;
}
};
class Bike:Vehicle{
private:
string bike_type;
public:
void setBike_Type(string t){
type = t;
}
string getBike_Type(){
return bike_type;
}
};
class Aircraft:Vehicle{
private:
short no_of_wings;
public:
void setNo_of_wings(short wings)
{
no_of_wings = wings;
}
short getNo_of_wings()
{
return no_of_wings;
}
};
class Car:Vehicle{
private:
string reg_no;
string type;
public:
void setType(string t)
{
if ((t=="Pneumatic") || (t=="Hydraulic"))
{
type = t;
}
else
{
cout<<"\nInvalid entry. Please enter the correct type:";
setType(t);
}
}
};
class Ship:Vehicle{
private:
bool has_radar_detection;
public:
void setRadar_Detection(bool r){
has_radar_detection = r;
}
bool getRadar_Detection(){
return has_radar_detection;
}
};
int x;
main()
{
Vehicle v;
Bike b;
Car c;
Aircraft a;
Ship s;
s.setStationary_state(true);
c.setType("xyz");
/*v.setStationary_state(true);
if (!(v.getStationary_state()))
{
cout<<"Vehicle is moving";
}
else
{
cout<<"Vehicle is at rest";
}
*/
getch();
}
What is really wrong there? What is the cause of the error and how to avoid it. Please explain in detail.
class has private default inheritance, so you would need to specify public, i.e.
class Ship : public Vehicle { }:
ans so on. struct has public inheritance as default.
You need to specify inheritance access level:
class Bike : public Vehicle
I.e. you need to make Vehicle a public base.
If you don't specify an access specifier, inheritance is automatically private.
You need to change these line:
class Ship:Vehicle
to this:
class Ship:public Vehicle
encapsulation is attained by placing related data in the same place and offering security to the data.include
private - access granted to same class
public - any code can access the data
protected - access granted to methods of the same class,friend class and derived class