What is issue in throwing an exception in a destructor?
If a destructor throws an exception, the instance is left in an invalid state. When an exception is thrown, the destructor automatically terminates at the point of the throw, unwinding the call stack until an exception handler is found (if one is provided). However, any resources yet to be released by the destructor, including all the instance's base classes, cannot be destroyed.
When writing your own destructors, it is important to never throw an exception. If an exception could be thrown from within your destructor, you must catch it and handle it within the same destructor -- you must not rethrow the exception.
There isn't one; C is strictly non object oriented. Although C++ is often considered to be an object-oriented extension for C (it was originally called C with Classes), it would be more accurate to describe them as siblings. The two have evolved separately and while they still retain a high-level of compatibility through their common ancestry, they are not the same language.
What is the difference between compilers and interpreters in c plus plus in tabular form?
C-compiler translates the C-source into Assembly or machine code.
On the other hand, C-interpreter -- well, there is no such thing as C-interpreter.
What is difference between define and typedef in c plus plus?
defines are handled by a preprocessor (a program run before the actual c compiler) which works like replace all in you editor. Typedef is handled by the c compiler itself, and is an actual definition of a new type. The distinction given between #define and typedef has one significant error: typedef does not in fact create a new type. According to Kernighan & Richie, the authors of the authoritative and universally acclaimed book, "The C Programming Language": It must be emphasized that a typedef declaration does not create a new type in any sense; it merely adds a new name for some existing type. Nor are there any new semantics: variables declared this way have exactly the same properties as variables whose declarations are spelled out explicitly. In effect, typedef is like #define, except that since it is interpreted by the compiler, it can cope with textual substitutions that are beyond the capabilities of the preprocessor. There are some more subtleties though. The type defined with a typedef is exactly like its counterpart as far as its type declaring power is concerned BUT it cannot be modified like its counterpart. For example, let's say you define a synonim for the int type with: typedef int MYINT Now you can declare an int variable either with int a; or MYINT a; But you cannot declare an unsigned int (using the unsigned modifier) with unsigned MYINT a; although unsigned int a; would be perfectly acceptable. typedefs can correctly encode pointer types.where as #DEFINES are just replacements done by the preprocessor. For example, # typedef char *String_t; # #define String_d char * # String_t s1, s2; String_d s3, s4; s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention. typedef also allows to delcare arrays, # typedef char char_arr[]; # char_arr my_arr = "Hello World!\n"; This is equal to
# char my_arr[] = "Hello World!\n"; This may lead to obfuscated code when used too much, but when used correctly it is extremely useful to make code more compat and easier to read.
How can you calculate the c program running time through c plus plus coding?
This is a big question... but I'll try for a shortish answer. Try to do things in approximately the following order.
1) Use the right algorithms. Look into the Big O efficiency of any algorithms you are using, and make sure there aren't more efficient algorithms available.
2) Think about trading using more memory for a faster algorithm. Perhaps pre-computing tables of intermediate results.
3) Use a profiler to see where the bottle necks are and try improving them.
4) Optimize the inner most loops using assembly language to get the last little bit faster.
5) Run it on a faster computer.
6) Make it run in parallel across many computers or CPUs. This is especially good on the newer Intel chips where you have access to multiple CPUs on one chip. Distributed network computing sometimes is a good idea. Cloud computing is another possibility these days.
7) Make sure that C really is the right answer. It might not be in all cases.
A more specific question might yield a more specific answer.
When do you make class virtual?
Whenever a derived class requires direct inheritance from a base class, even if it inherits that base class indirectly. That is, if V is a base class from which B is derived, and D is derived from B, then D inherits from V indirectly (through B). But if B is virtually derived from V, then D will inherit directly from V.
This feature is commonly used in conjunction with multiple inheritance. Examine the following declarations:
class V{};
class B1: public V{};
class B2: public V{};
class M: public B1, public B2{};
Now suppose you have the following code:
M m; // Declare an instance of M.
V& v = m; // Ambiguous...
The problem with this is that M inherits V from both B1 and B2, and therefore inherits two separate instances of V. The compiler is unable to determine which instance of V you want to refer to. One solution to this would be to use static casts to indirectly refer to an explicit instance of V:
V& v = static_cast<B1&>(m);
or
V& v = static_cast<B2&>(m);
While this is certainly workable, it is an ugly approach that places far too much responsibility upon the programmer to ensure the correct instance of V is being referred to. However, unless there is a specific need to have two instances of V within M, the problem can be resolved with virtual inheritance.
By virtually deriving both B1 and B2 from V, M will directly inherit just one instance of V, which is then shared, virtually, between B1 and B2:
class V{};
class B1: public virtual V{};
class B2: public virtual V{};
class M: public B1, public B2{};
M m;
V& v = m; // No ambiguity.
Now M can access all the members of V directly, as can B1 and B2, because they now share the same instance of V.
Note that it doesn't matter whether the virtual keyword is placed before or after the access specifier (which is public in this case). "virtual public" and "public virtual" have the same meaning.
Write a program using c plus plus to whether the given square matrix is symmetric or not?
int sym_test (const int **a, int n) {
int i, j, sym;
i=1, j=0, sym=1;
while (sym && i
else if (j
}
return sym;
}
What is single inheritance in c plus plus?
Multiple inheritance occurs when a class is derived directly from two or more base classes.
class b1 {};
class b2 {};
class d: public b1, public b2 {}; // multiple inheritance class
Write a c plus plus programs for stack using arrays?
//Program on Stack ADT Using Arrays
#include<iostream.h>
#include<conio.h>
#define maxSize 10
#include<stdlib.h>
class stack
{
public:
stack(); // constructor call the display function
void pop(); //used to pop the value as per user demand
void push(); //used for push the value as per user demand
int empty(); //used to check the stack
int full(); //used to check the stack whether it is full as max limit is 80
void display(); //used to display menu for operations
void stackDisplay(); //used to display whole stack items
void operation(); //used to enter the user choice
private:
int top;
int item[maxSize];
};
stack::stack()
{
top = 0;
display();
}
void stack :: display()
{
cout << "STACK MAIN MENU GIVEN BELOW" << endl;
cout << "PRESS 1 FOR PUSH THE ITEM ON STACK" << endl;
cout << "PRESS 2 FOR POP THE ITEM ON STACK" << endl;
cout << "PRESS 3 FOR DISPLAY THE WHOLE STACK" << endl;
cout << "PRESS 4 FOR EXIT THE PROGRAM" << endl;
cout<<"ENTER YOUR CHOICE" << endl;
operation();
}
void stack :: operation()
{
int choice;
cin >> choice;
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
stackDisplay();
break;
case 4:
exit(4);
default:
cout << "PLZ ENTER VALID NUMBER" <<endl;
operation();
}
}
int stack::empty()
{
if( top 0)
{
cout<<"THE STACK IS EMPTY UNDERFLOW" << endl;
cin.get();
}
else
{
char ch;
cout<<"AS THE LAST ELEMENT IN STACK IS "<<item[top] << endl;
top = top-1;
cout<<"WANT TO POP OUT ANOTHER ELEMENT y/n" << endl;
cin>>ch;
if(ch=='y')
pop();
cin.get();
}
cout<<"PRESS ENTER TO GO TO MAIN MENU " << endl;
cin.get();
clrscr();
display();
}
void stack::stackDisplay()
{
cout<<"THE ELEMENTS IN STACK IS"<<endl;
for(int i = 1;i <= top; i++)
{
cout << item[i] << endl;
}
cin.get();
cout<<"PRESS ENTER FOR MAIN MENU " << endl;
cin.get();
clrscr();
display();
}
void main()
{
clrscr();
gotoxy(15,10);
cout<<"WELCOME TO THE PROGRAM OF STACK MADE BY SAURABH " << endl;
gotoxy(15,11);
cout<<"________________________________________________" << endl;
cin.get();
clrscr();
stack obj;
getch();
}
BY. SAURABH (GNDU RC JAL CSE 2nd YEAR)
Write a c program to print fibonacci series using do while loop?
#include<iostream>
using namespace std;
#define MIN 1
#define MAX 1000000
int main()
{
int num;
char c;
do
{
cout << "Enter a number from " << MIN << "-" << MAX << " (0 to quit): ";
cin >> num;
while(cin.fail() num < 0 num > MAX)
{
if( cin.fail() )
{
cin.clear();
cin >> c;
}
cout << "Invalid number, try again: ";
cin >> num;
}
if(num)
{
cout << "\nFibbonacci series for n, where 1 <= n <= " << num << ":\n\n";
int n = 1, x = 0, y = 0;
do
{
cout << n;
x = y;
y = n;
n = x + y;
if( n < num )
cout << ", ";
}while( n < num );
cout << endl << endl;
}
}while( num );
return( 0 );
}
Why is a destructor function required in C plus plus classes?
A destructor is not a function per-se. Functions have returns values but destructors do not (not even void). However, other than the lack of a return value, a destructor's body is no different to a function body.
Contrary to belief, destructors are not required by every class of object. Destructors are only required when we need to explicitly release a resource when an object of the class falls from scope, but not all resources need to be released explicitly. Consider the following class:
struct point {
int x, y;
};
This class does not require a destructor because it is self-contained. That is, all the resources consumed by an object of the class are contained within the object itself, thus when the object falls from scope, the memory it consumed is automatically released. There is nothing to destroy.
Now consider the following class:
class my_vector {
std::vector<int> v;
};
Again, this class requires no destructor. When objects of this class fall from scope, the vector's destructor is invoked, releasing its resources. Thus the only resource consumed by this class is the vector itself, and that's self-contained by the class.
Now let's consider a class that does require a destructor:
template<typename T>
class smart_pointer {
T* ptr;
// ...
};
Here, we have a class that encapsulates a "naked" pointer variable of some type T. That pointer could feasibly refer to any object of type T in memory. However, being a "smart pointer", the assumption is that objects of this class will "own" the memory they refer to. As the owner, it makes sense to yield ownership whenever object's of the class fall from scope. If we didn't provide a destructor, ptr would fall from scope, but the memory it referred to would not. So to ensure the memory is released, we must explicitly release it via the class destructor:
template<typename T> class smart_pointer {
T* ptr;
// ...
public:
~smart_pointer () { delete ptr; }
};
To summarise: a destructor is only required when an object acquires a non-shared resource that is not released automatically when objects of the class fall from scope. A vector is a resource handle, so when it falls from scope, its resources are released automatically. Similarly with smart pointers. However a "naked" pointer is not a resource handle, so if our class "owns" a resource by holding a pointer to it, then we must release that pointer when objects of the class are destroyed. Resources cover many things besides raw memory. If we hold a reference to an open file, it would be prudent to close the file before the reference falls from scope. With a resource handle we get that assurance. Thus if we use resource handles rather than "raw" resources, then we need never write any destructors.
There can be other reasons to require a destructor besides resource management, such as to write an entry in a log file upon destruction, however resource management and other "housekeeping" task are not a requirement of every class thus a destructor is not required by every class.
Why objects are not used to acces the static class members?
Static members are members of the class, not an instance of the class.
All instances of a class have access to all their static members. Derived classes have access to both protected and public statics, while public statics are fully accessible.
Think of static members as being global variables or functions, but scoped to the class rather than being globally accessible (and therefore publicly accessible).
Consider the following example. A private static member variable, count, is declared. Note that it must be initialised immediately after the class declaration, but outside of a code block. Were it declared public it could be initialised in a code block, but the class needs to maintain control over it, thus it is completely hidden from all outside influence.
The two constructors increment count while the destructor decrements count. Thus count maintains a running total of all the instances of the class (much like a reference counter). Note that all instances of the class have direct access to the static member. Note also that if other parametrised constructors are declared, each must increment countindependently.
The public static accessor method, GetCount(), returns the current value of count (returning by value, not by reference). There is no equivalent set mutator, thus countis a read-only variable -- it cannot be altered from outside of the class.
#include
class MyClass{
public:
MyClass(){ ++count; }
MyClass(const MyClass & copy){ ++count; }
~MyClass(){ --count; }
public:
static unsigned int GetCount(){ return( count ); }
private:
static unsigned int count;
};
// Initialise the static member:
unsigned int MyClass::count = 0;
void PrintCount()
{
printf( "There %s currently %u instance%s of MyClass.\n",
MyClass::GetCount() 1 ? "" : "s" );
}
int main()
{
MyClass * myClass[10];
// At this point there are no instances.
PrintCount();
printf( "\nCreating instances of MyClass...\n" );
for( int i=0; i<10; ++i )
{
myClass[i] = new MyClass();
PrintCount();
}
printf( "\nDestroying instances of MyClass...\n" );
for( int i=0; i<10; ++i )
{
delete( myClass[i] );
PrintCount();
}
return( 0 );
}
How do you compile and run C programs on the Macintosh?
The first step is to install the XCode developer tools that comes with OSX. You can do this by looking on your OSX install disc. There should be a folder for optional installs, and a package for XCode. This will automatically install gcc, a C compiler, on your machine. Next, find the Console in the Utilities folder. It opens a UNIX shell. Move to the directory that your c file is in (you can find more information about UNIX elsewhere if you need to). Let's say your C file is named myfile.c. To compile it, type: gcc myfile.c This will compile your program, and name the compiled program a.out. To run it, type: ./a.out I hope that helps. Brina
Who invented c plus plus and when?
C++ was originally called 'C With Classes' in 1978, and was renamed by its developer, Bjarne Stroustrup, in 1983. The new name literally meant 'the successor to C', although it should really have been called ++C (prefix increment) rather than C++ (postfix increment), since the former returns C+1 (the successor to C), while the latter returns C.
Write a c plus plus program of array to pointers?
#include
void
printarr(int
a[]);
void
printdetail(int
a[]);
main()
{
int
a[5];
for
(int
i = 0;i<5;i++)
{
a[i]=i;
}
printdetail(a);
}
void
printarr(int
a[])
{
for
(int
i = 0;i<5;i++)
{
printf("value in array %d\n"
,a[i]);
}
}
void
printdetail(int
a[])
{
for
(int
i = 0;i<5;i++)
{
printf("value in array %d and address is %8u\n"
,a[i],&a[i]);
}
}
void
print_usingptr(int
a[])
{
int
*b;
Explain term composition with example in c plus plus?
Composition relates to the way in which complex objects can be constructed from smaller, simpler objects. We refer to this as object composition. While simple objects typically contain one or more embedded primitive member attributes, such as int, char, float and so on, composite objects typically embed other objects (often in addition to other primitive attributes), and each of those objects may themselves be composite or they may be simple. This allows highly complex object models to be constructed such that each object within a composition is self-contained and ultimately operates no differently to how it would operate if it were a standalone object. The composite object effectively acts as an object coordinator, calling specific methods upon the simpler objects as required. In other words, the actual workload is delegated to the object or objects that are actually responsible for that workload, and they themselves may delegate to simpler objects, and they to theirs. The composite object's only real workload is in processing any relevant results of those delegations. In other words, a simple function call through a member method of the composite object can produce a cascade of member methods within the embedded objects, each of which works completely independently, but the results of which can be combined by the containing object in order to produce highly complex behaviour.
By way of an example, a motor car is built up from thousands of individual but ultimately simple components, such as nuts and bolts, switches, cogs, levers, wheels and so on. Some of those simple objects are combined to produce more complex objects, such as an engine, a transmission unit, a steering mechanism, door locks, and so, on. Ultimately, they all combine to produce a car. But no matter how complex a composite object is, the behaviour of their embedded objects does not change: a nut and bolt is still a nut and bolt whether it is holding a door hinge onto a chassis, or a suspension strut to a wheel hub. In other words, the job of physically holding one component to another is delegated to the nut and bolt, but is coordinated according to the object that embeds the nut and bolt, while that object is coordinated and delegated to by the object that contains it, and so on.
Selection Sort Program in c and c plus plus?
The following code demonstrates the implementations for bubble sort, insertion sort and selection sort, in C++.
#include<iostream>
#include<time.h>
#include<iomanip>
#include<string>
void swap(int& x, int& y)
{
x^=y^=x^=y;
}
void bubble_sort(int* A, int size)
{
while(size)
{
int n=0;
for(int i=1; i<size; ++i)
{
if(A[i-1]>A[i])
{
swap(A[i-1], A[i]);
n=i;
}
}
size=n;
}
}
void insertion_sort(int* A, int size)
{
for(int i=1; i<size; ++i)
{
int value=A[i];
int hole=i;
while( hole && value<A[hole-1] )
{
A[hole]=A[hole-1];
--hole;
}
A[hole]=value;
}
}
void selection_sort(int* A, int size)
{
for(int i=0; i<size-1; ++i)
{
int j=i;
for(int k=i+1; k<size; ++k)
if(A[k]<A[j])
j=k;
if( i!=j )
swap(A[i],A[j]);
}
}
void sort(int* A, int size, int sort_type)
{
switch(sort_type)
{
case(0): bubble_sort( A, size );
case(1): insertion_sort( A, size );
case(2): selection_sort( A, size );
}
}
int* copy_array(int* A, int size)
{
int* copy=new int[size];
memcpy(copy, A, size*sizeof(int));
return(copy);
}
void print_array(int* A, int size, char* prompt)
{
std::cout<<prompt<<"\t";
for(int i=0; i<size; ++i)
std::cout<<std::setw(2)<<A[i]<<" ";
std::cout<<std::endl;
}
int get_rand(int range_min=0, int range_max=RAND_MAX)
{
return((int) ((double)rand() / (RAND_MAX + 1) * ((range_max + 1) - range_min) + range_min));
}
int input_char(std::string prompt, std::string input)
{
char ch;
do
{
std::cout<<prompt<<": ";
std::cin>>ch;
}
while(input.find(ch)==std::string::npos);
return(input.find(ch)%(input.size()/2));
}
int main()
{
srand((unsigned) time(NULL));
int size = get_rand( 10, 80);
if( int* A = new int[size] )
{
for( int i=0; i<size; ++i )
A[i]=get_rand( 1, size );
int choice=input_char("Please select a sorting method:\n[B]ubble, [I]nsert, [S]election", "bisBIS");
std::cout<<"You chose ";
switch(choice)
{
case(0): std::cout<<"bubble"; break;
case(1): std::cout<<"insertion"; break;
case(2): std::cout<<"selection"; break;
}
std::cout<<" sort...\n"<<std::endl;
print_array( A, size, "Before sorting" );
sort(A, size, choice);
print_array( A, size, "After sorting" );
delete [] A;
}
return(0);
}
Why does C plus plus allows static binding and not dynamic binding?
Dynamic binding, or late binding, is when the object code for the class does not get loaded into memory until it is needed. This saves time at module load time, at the cost of delayed execution for the first invocation.
In c plus plus Who tells the compiler that a specific class will be declared later in the program?
A forward declaration. However forward declarations can only be used when the class is used as a pointer or reference prior to its definition, otherwise it must be defined before it is used.
class A; // forward declaration
class B {
A& data; // reference to class that has yet to be defined
};
class A {}; // definition
Data structure is important since it dictates the types of operations we can perform on the data and how efficiently they can be carried out. It also dictates how dynamic we can be in dealing with our data; for example it dictates if we can add additional data on the fly or if we need to know about all of the data up front. We determine which data structures to use to store our data only after we've carefully analyzed the problem and know at least what it is we hope to do with the data; for example if we'll require random access, or sequential access, or the ability to move both forward and backward through the data.
What is the if-else statement in c plus plus programming language?
The if-then-else inline command is shown below:
returnvalue = (condition) ? (truePart) : (falsePart);
-----------
According to the C standard, this command does exist in the C coding language in the same way as it exists in C++ and comparable languages.
http://users.ece.cmu.edu/~eno/coding/CCodingStandard.html
What is the difference between function prototyping and function overloading?
Function prototypes determine the return type, the name of the function, the argument types expected by the function, and the arity of the function. Function prototyping is used to separate interface from implementation. In C++ all functions must be declared before they are called, thus we use prototypes to provide forward declarations for those functions that have yet to be defined/implemented. We can also use forward declarations for incomplete types such as template functions and classes, however the definition/implementation must be visible to compiler before the function or class is used. In these cases the definitions are typically placed in the same header as the declarations.
It is important to note that a definition is also a declaration, and therefore both are also prototypes. The only real difference is that prototypes do not require names for the formal arguments. Even if you provide argument names in your prototypes, they will be ignored by the compiler. The argument names within the definition are the only names of any relevance.
Function overloading is where two or more functions share the same name within the same namespace, but have different signatures. The signature of a function is essentially the same as its prototype but excludes the return type, thus overloads cannot differ by return type alone. The compiler uses the function signature to differentiate between your overloads.
All function signatures within a namespace must be unambiguous, thus you cannot have two functions with the same name and arguments that are co-variant. For example, the following overloads are invalid because a size_t type is co-variant with unsigned int type, thus the compiler cannot differentiate them.
unsigned int max(unsigned int, unsigned int);
size_t max(size_t, size_t);
What is the meanig of return 0 in c plus plus?
The return statement "returns" control to the function that invoked the function executing the return statement. Adding a value, such as return 0, adds a "return value", which the invoking function can inspect. The type of the returned value is declared along with the function's declaration, such as int myfunction(...) - it can be any type, not just an int.
If the "invoking function" is the operating system, the return statement returns control back to the operating system. The value of the return, in this case an int, tells the operating system what the result of the execution of the entire program was.
By convention, but this is operating system, shell, and/or programmer determined, a return value of 0 normally means "success", while anything else means "some kind of error", and the actual value identifies what kind of error.
Write a program in c plus plus to create an analog and digital clock using computer graphics?
#include "stdio.h"
#include "conio.h"
#include "dos.h"
void main()
{
int h,m,s;
h=0;
m=0;
s=0;
while(1)
{
if(s>59)
{
m=m+1;
s=0;
}
if(m>59)
{
h=h+1;
m=0;
}
if(h>11)
{
h=0;
m=0;
s=0;
}
delay(1000);
s=s+1;
clrscr();
printf("\n DIGITAL CLOCK");
printf("\n HOUR:MINUTE:SECOND");
printf("\n%d:%d:%d",h,m,s);
}
getch();
}
Definition of structure in c plus plus?
A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. A structure declaration forms a template that may be used to create structure objects (that is, instances of a structure). The variables that make up the structure are called members. (Structure members are also commonly referred to as elements or fields).