parsecer February 2016

Create a static class variable inside another class, use of deleted function = error

I have a class Dog and a class Owner. In class Dog there is a member which is a reference to a specimen of class Owner (breeder). So i need this specimen to be created when i have at least 1 Dog specimen and to be shared and used in their constructors by other Dog examplars.

class Dog 
    {
       private:
         Owner & m_owner;
         ...
       public:
           static Owner & m_breeder;
         ...
    }

class Owner
    {private:
         ...
     public:
         ...
      }

dog.cpp

  {
    #include "dog_class.h"
    #include <iostream>
    #include <cstdlib>
    #include <string>
    #include <ctime>

    Owner breeder("breeder");
    Owner & Dog::m_breeder=breeder;
    //methods here
    Dog () : m_owner(m_breeder) {}

    ...
  }

This doesn't work (error:use of deleted function 'Dog & Dog::operator=(const Dog&); I tried to include Owner as "static Owner breeder;" in public section of class Dog and later initialize it inside dog.cpp but it doesn't work either. What's wrong and how my goal can be obtained?


Here some more code, basically, constructors of class Dog and Owner:

dog_class_methods.cpp

Dog::Dog(std::string name, int size, int status, int loyalty, int sex, int price, std::vector<Dog> * market, Owner & owner) : m_owner(owner)
{
m_name=name;
m_size=size;
m_status=status;
m_loyalty=loyalty;

m_sex=sex;
m_price=price;
m_market=market; //pointer to the market
m_market->push_back(*this);
//break_out();
 }



  Dog::Dog() : m_owner(m_breeder)
{
m_name="Fang";
srand(time(NULL));
m_size=(rand()%10)+1; //small: random number from 1 to 10;
m_status=0; //not owned
m_loyalty=(rand()%10)+1; //from 1 to 10
Owner no_one("no_one");
//m_owner=no_one;
m_sex=rand()%2; //rand 0 or 1;
m_price=rand()%1001; //0 - 1000;
//show_data();
//break_out();
 }

owner_class_methods.cpp

        

Answers


Hal February 2016

class Dog {
    Dog(Owner& owner)
    : m_owner(owner)
    {}
    Owner& m_owner;
};

Owner breeder("breeder");
Dog the_dog(breeder);


parsecer February 2016

The error appeared because there was a use of vector which required for Dog objects to be copyable, but there was a reference member in class and operator= needed to be written:

  Dog Dog::operator=(const Dog & a)
 {    m_owner=a.m_owner;
      m_loyalty=a.m_loyalty;
      m_size=a.m_size;
      m_status=a.m_status;
      m_sex=a.m_sex;
      m_price=a.m_price;
      m_market=a.m_market; //market один для всех собак;
      m_name=a.m_name;
      return *this;
 }

This solved the whole thing.

Post Status

Asked in February 2016
Viewed 1,563 times
Voted 10
Answered 2 times

Search




Leave an answer