Click here to Skip to main content
15,846,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to Polymorphism. I am trying to assign values in class whose objects are declared to heap memory.(with new keyword). How can I call the function setvalues without object of classes.

What I have tried:

#include <iostream>
using namespace std;
class person{

protected:
    string name;int age;
public:
    virtual string getName();
    virtual int getAge();


};
class Admin : public person{
    public:
    void setvalues(string n, int a)
    {
        name=n;
        age=a;

    }
    string getName()
    {
        return name;
    }
    int getAge()  {
        return age;
        }
};
    class Faculty : public person{
        public:
    void setvalues(string n, int a)
    {
        name=n;
        age=a;

    }
    string getName()
    {
        return name;
    }
    int getAge()  
        {
        return age;
        }

};
int main()
{
    person *p;
    new Admin[5];
    new Faculty[5];



 string name1[5]={"saad","zaman","arslan","qaiser","qasim"};
        string name2[5]={"adil","abdullah","salal","shehzad","boss"};
        int age1[5]={20,21,24,23,25};
        int age2[5]={31,33,34,19,45};

        for(int i=0; i<5; i++)
        {
     //////// how to assign values admin and feculty objects as we cannot call function without object
        }
}
Posted
Updated 21-Apr-22 9:08am

I would suggest you add a constructor to your classes (and a destructor if needed).
For example
C++
class person {
private:
    string name;
    int age;
public:
    person(string nm, int a) 
        : name(nm), age(a) //initializes person's name and age from parameters
        {} // no body needed
    // ...
}; 

You can then create new object using the constructor as follows
C++
person *p = new person("Jim", 42);
Don't forget to delete the object when you're done with it.

These days, though, smart pointers std::unique_ptr and std::shared_ptr are preferred, as they follow the expected RAII principle, and will release the memory when the object goes out of scope.
 
Share this answer
 
Comments
Hamza Jameel 21-Apr-22 12:15pm    
I am trying to create array of objects and then need to assign data to each object through array of data.All constructors are called after creating array of object. :). To assign data we need setdata function. then what is use of constructor here.
k5054 21-Apr-22 12:57pm    
I didn't look too closely at your code .. the problem is here
int main(){    new Admin[5];
While that does create an array of 5 new Admin objects on the stack, it does not associate it with any variable try instead
Admin *admins = new Admin[5];
// ...
     admins[1].setvalues(/* ... */); 
In modern C++ about the only time you should be using a plain array is if you need to handle a C string, i.e. char mystring[10] or if you need to interface with a C function that manipulates an array. Otherwise, 99% of the time you want a std::vector For example
C++
#include <vector>
#include <iostream>

class person {
private:
    std::string name;
    int age;
public:
    person(std::string nm, int a) : name(nm), age(a) {}
    string get_name() { return name; }
    int get_age() { return age; }
};

int main()
{
    string name1[5]={"saad","zaman","arslan","qaiser","qasim"};
    int age1[5]={20,21,24,23,25};
  
    std::vector<person> people;
    for(int i = 0; i < 5; ++i)
    {
        person p(name1[i], age1[i]);
        people.push_back(p);
     }

    for(const auto p : people)
        std::cout << p.get_name() << " " << p.get_age();
}
Better yet, you can initialize an of objects using the extended initializer syntax
C++
std::vector<person> people = {
    {"saad", 20},
    {"zaman", 21},
    {"arslan", 24},
    { "qaiser", 23},
    { "qasim", 25}
 };
This does require C++ 11 or later, though.
 
Share this answer
 
Comments
merano99 21-Apr-22 18:38pm    
Almost fine, but would have a two comments:

1. The compiler complains about the const declaration: this pointer cannot be converted from "const person" to "person &".

2. Missing <string> include and code should use std::string.
You could change your code this way
C++
#include <iostream>
using namespace std;
class person{

protected:
    string name;int age;
public:
    virtual string getName()=0;
    virtual int getAge()=0;
    virtual void setvalues( string n, int a)=0;
    virtual ~person(){};
};
class Admin : public person{
    public:

   ~Admin(){}
    void setvalues(string n, int a)
    {
        name=n;
        age=a;

    }
    string getName()
    {
        return name;
    }
    int getAge()  {
        return age;
        }
};
    class Faculty : public person{
        public:
    ~Faculty(){}
    void setvalues(string n, int a)
    {
        name=n;
        age=a;

    }
    string getName()
    {
        return name;
    }
    int getAge()
        {
        return age;
        }

};
int main()
{
    person *p[4];

    p[0] = new Admin();
    p[1] = new Faculty();
    p[2] = new Admin();
    p[3] = new Faculty();


    string name1[2]={"saad","zaman"};
    string name2[2]={"adil","abdullah"};
    int age1[5]={20,21};
    int age2[5]={31,33};

    for(int i=0; i<4; i++)
    {
      int hi = i /2;
      if ( (i % 2) == 0 )
      {
        p[i]->setvalues(name1[hi], age1[hi]);
      }
      else
      {
        p[i]->setvalues(name2[hi], age2[hi]);
      }
    }

    for (int i=0; i<4; ++i)
    {
      cout << p[i]->getName() << " " << p[i]->getAge() << endl;
    }


    //...
    for (int i=0; i<4; ++i)
    {
      delete p[i];
    }


Please note, there are far better ways to do that (or something more useful) in C++, as others already suggested.

[update]
A tiny bit of polymorphism using the standard library:
C++
#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class Person
{
public:
  virtual void show() const = 0;

  virtual ~Person(){}
};

class Admin : public Person
{
  string m_name;

public:
  Admin(string name):m_name(name){}
  ~Admin(){}
  void show() const { cout << "Admin " << m_name << endl; }
};

class Faculty : public Person
{
  string m_name;

public:
  Faculty(string name):m_name(name){}
  ~Faculty(){}
  void show() const {  cout << "Faculty " << m_name << endl; }
};


int main()
{
  vector < unique_ptr< Person >  > v;
  v.push_back( make_unique<Admin>("Foo") );
  v.push_back( make_unique<Faculty>("Bar") );

  for (const auto & p : v)
    p->show();

}

[/update]
 
Share this answer
 
v2
Comments
Patrice T 22-Apr-22 3:06am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900