Click here to Skip to main content
15,891,993 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi
I have to create exact number of objects in c++
Ex:
C++
class Test
{
public:
Test()
{

}
}
int main()
{
 Test t1,t2,t3;
 // if i will create 4th object then it has to throw the exeception.
}
Posted
Updated 18-Jun-15 10:13am
v2
Comments
bijaynayak 19-Jun-15 2:58am    
Hi Kryukov,
Thi is what i tried and got the solutions either correct me

Create a static counter, and increment it in the Text class constructor.
If it reaches four, throw your exception.
 
Share this answer
 
C#
#include<iostream>

using namespace std;
class Test
{
    static int count;
public:
    Test()
    {
        count++;
        if(count==4)
        {
            throw int();
        }
        cout<<count<<endl;
    }
};

int Test::count=0;
int main(int argc, char *argv[])
{
    try
    {
        for(int i=0;i<10;i++)
        {
            Test *t1=new Test[i];
        }
    }
    catch(int)
    {
        cout<<"in catch block";
    }

    return 0;
}
 
Share this answer
 

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