Anonymous Class Objects
Table of Contents

Introduction

  • It is possible to construct anonymous objects of our own class types.
  • This is done by creating objects like normal, but omitting the variable name.
  • Anonymous variables are primarily used either to pass or return values without having to create lots of temporary variables to do so.

Examples

Example

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    int GetCents() { return m_nCents; }
};
 
Cents Add(Cents &c1, Cents &c2)
{
    Cents cTemp(c1.GetCents() + c2.GetCents());
    return cTemp;
}
 
int main()
{
    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = Add(cCents1, cCents2);
    std::cout << "I have " << cCentsSum.GetCents() << " cents." << std::endl;
 
    return 0;
}

We can simplify the above program by using anonymous variables.

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    int GetCents() { return m_nCents; }
};
 
Cents Add(Cents &c1, Cents &c2)
{
    return Cents(c1.GetCents() + c2.GetCents());
}
 
int main()
{
    Cents cCents1(6);
    Cents cCents2(8);
    std::cout << "I have " << Add(cCents1, cCents2).GetCents() << " cents." << std::endl;
 
    return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.