answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How do you define a constructor function for a Date class that initializes the Date objects?

The following is one possible method. If the input arguments would result in an invalid date (or no arguments are given), then the members are set to an arbitrary default date (in this case 1/1/1980).

An alternative method that ensures all dates are valid (non-default) would be to throw an exception from the set() member. If your code is producing invalid date arguments (causing the exception to be thrown) then you really need to fix the code that generates those dates. Note that the static methods, is_valid() and is_leap_year(), can be used to check date arguments without actually constructing a date object.

Another alternative would be to set a flag that denotes if the date object is valid or not. However, this is the least intuitive method as the onus is then placed upon the user to always check the flag before using the object.

#include<iostream>

#include<iomanip>

class cdate

{

unsigned m_day;

unsigned m_month;

unsigned m_year;

public:

cdate (unsigned day, unsigned month, unsigned year): m_day(1), m_month(1), m_year(1980) { set (day, month, year); }

cdate (const cdate& date): m_day(date.m_day), m_month(date.m_month), m_year(date.m_year) {}

cdate& operator= (const cdate& date) { m_day=date.m_day; m_month=date.m_month; m_year=date.m_year; }

bool set (unsigned day, unsigned month, unsigned year);

static bool is_valid (unsigned day, unsigned month, unsigned year);

static bool is_leap_year (unsigned year);

unsigned day() const { return m_day; }

unsigned month() const { return m_month; }

unsigned year() const { return m_year; }

};

bool cdate::is_valid (unsigned day, unsigned month, unsigned year)

{

// handle zeroes

if (!day !month !year)

return false;

// handle invalid month

if (month>12)

return false;

// handle 31 day months

if ((month==1 month==3 month==5 month==7 month==8 month==10 month==12) && day>31)

return false;

// handle 30 day months

if ((month==4 month==6 month==9 month==11) && day>30)

return false;

// handle leap years

if (month==2)

{

if (!is_leap_year (year) && day>28)

return false;

else if (day>29)

return false;

}

// data ok

return true;

}

bool cdate::is_leap_year(unsigned year)

{

// common year (not divisible by 4)

if (year%4)

return false;

// leap year (not divisible by 100)

else if (year%100)

return true;

// leap year (divisible by 400)

else if (year%400==0)

return true;

// common year

return false;

}

bool cdate::set (unsigned day, unsigned month, unsigned year)

{

if (is_valid (day, month, year))

{

m_day = day;

m_month = month;

m_year = year;

return true;

}

// alternatively, throw an exception here

return false;

}

std::ostream& operator<< (std::ostream& os, const cdate& date)

{

os

<< std::setw (2) << std::setfill('0') << date.day() << '/'

<< std::setw (2) << std::setfill('0') << date.month() << '/'

<< std::setw (4) << std::setfill('0') << date.year();

return os;

}

int main ()

{

// invalid date (was not a leap year)

std::cout << "Input:\t29/02/1900" << std::endl;

cdate d1(29,2,1900);

std::cout << "Output:\t" << d1 << std::endl;

// valid date (was a leap year)

std::cout << "Input:\t29/02/2000" << std::endl;

cdate d2(29,2,2000);

std::cout << "Output:\t" << d2 << std::endl;

}

What does try and finally mean in C plus plus programming?

You mean try and catch. There is no finally in C++; it is not required because RAII (Resource Acquisition Is Initialisation) renders it redundant.
A try block provides the primary means of handling runtime errors in C++:

int main () {
try {
std::string().at(1); // throws!
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
}
}


Example output:
invalid string position


A catch block is an exception handler for a given type of exception. Every try block must have at least one catch block but we can have as many catch blocks as required to handle different types of exceptions and deal with each one accordingly. The std::exception class is just one type of exception.

The point at which an error is detected can often be quite far-removed from the point at which the error can be handled. The above example isn't the sort of code you'd find in a real-world application; it's fairly obvious where the problem lies because we deliberately forced an exception to be thrown via the tryblock and the error message is reasonably self-explanatory. But in the real-world we're more likely to see code similar to the following:

int main () {
try {
do_a_task(); // might throw
do_another_task(); // might throw
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
}
}



If any exception is thrown there are two possible sources for that error. The more complex those functions are the more difficult it becomes to locate the errant code. Indeed, the error could originate from a deeply-nested series of function calls from within either of these two functions.

However, it is not actually necessary to know where an error occurs in order to handle the error. It is enough to know that the error has been caught. It's the ones we don't catch that we really need to worry about because an unhandled exception will terminate our program without any warning. Worse, whatever message the exception carried with it will be lost forever (we'd need to use a debugger to determine why the program aborted).

Production code will often place a series of specific exception handlers in main(), along with a somewhat convoluted catch-all to try and catch any and all unknown exception types:

int main () {
try {
do_a_task(); // might throw
do_another_task(); // might throw
} catch (const int& i) {
std::cerr << i << " : some idiot threw an integer!" << std::endl;
} catch (const char* s) {
std::cerr << s << std::endl;
} catch (const std::string& s) {
std::cerr << s << std::endl;
} catch (...) {
std::exception_ptr eptr {std::current_exception()};
try {
if (eptr) std::rethrow_exception (eptr);
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
} catch (...) {
std::cerr << "unknown exception type" << std::endl;
}
}


Note that catch (...) is the catch-all handler but even this cannot be guaranteed to catch all errors, particularly if we make extensive use of third-party libraries. Programmers that throw meaningless integers instead of well-defined exception classes derived from std::exception are a particular annoyance, because two different libraries might use the same integer value to represent two completely different exceptions. Then there are those who persist in throwing C-style strings or (worse) std::string objects. Then there are those who detest the standard library to such a degree they will re-invent the wheel and throw ad-hoc exception classes into the mix.

Some implementations may provide proprietary methods that will catch any and all exceptions, however the code is not portable.


Some exceptions simply cannot be caught because they are not exceptional. Division by zero is a common example. This is not an exception because any code that allows a divide by zero operation has undefined behaviour. As such, the entire program is invalid and no amount of exception handling will turn an invalid program into a valid one. Note that division is a low-level machine operation, not a high-level function. The only way to prevent a divide by zero error is to not do it. Always check your denominators are non-zero! This is no different to ensuring a pointer is non-null before attempting to dereference it. But if you use smart pointers instead of "naked" pointers you get automatically get all the benefits of exception handling at no cost. Indeed, the fewer runtime tests you perform the more efficient your code will be.

State and explain any 4 predefined data types in C plus plus programming?

A char is always 1 byte long, but may be signed or unsigned depending on the implementation. Explicitly signed or unsigned char types are treated as being independent types from the implicit char type (3 separate types).

A short (or short int) is at least 2 bytes long while a long (or long int) is at least 4 bytes long. Both are implementation-dependent with regard their actual size and sign, but, like char, may be explicitly signed.

Char, short and long are used to store integers (whole numbers). A char can store signed values in the range -128 to +127, or unsigned values in the range 0 to 255.

A double is at least 8 bytes long while its shorter counterpart, a float, is at least 4 bytes long. Both are implicitly signed, floating point values.

To determine the length of any type (including predefined types) us the sizeof operator.

When you use Visual C plus plus which window do you use to change the attributes of a form?

There should be "Properties" window. If you do not see, you can make it visible if you go to "View"-> "Properties".

What is the C plus plus coding for implementation of queue using circular linked list?

The implementation is the same as that for a singly-linked list, the only difference being that rather than maintaining separate pointers to both the head and tail, you only need to maintain a pointer to the tail, since the tail's next node is always the head, which will be itself if there is only one node. As with all queues, insertions occur at the tail and extractions occur at the head.

Is g plus plus similar to c plus plus?

G++ is the Gnu compiler's extension for C++. It is not a different language. It simply allows you to use the GCC compiler to write C++ code.

Can include files be nested in c?

Yes, include files can be nested in C and C++. In fact, most library implementations do just that.

What is meant by heap in c or cpp?

If you see the word "heap" in the context of C/C++ programming, it is probably referring to one of two ideas.

First, if it is written as "the heap", it is probably referring to dynamically allocated memory. We conceptualize memory as either being on "the stack" or "the heap" in main memory. Memory allocation from the heap happens when a call to malloc (or similar functions) are called in C, or when the "new" operator is used in C++. This is in contrast to statically allocated memory, which comes from the load module and is known at compile-time, or from the "stack" which is used at run-time to allocate local scope, or automatic, memory.

Another usage of the word heap is a certain data structure called a heap. It is a very common data structure for priority queues and is crucial to the famous HeapSort algorithm. You can easily find more information on this data structure e.g. by searching for HeapSort.

Implement a class stack which simulates the operations of the stack allowing LIFO operationsAlso implement push and pop operations for the stack?

/* C program to implement stack. Stack is a LIFO data strcuture LIFO - Last in First Out Perform PUSH(insert operation), POP(Delete operation) and Display stack */

#include

#include

#define MAXSIZE 5

struct stack /* Structure definition for stack */

{

int stk[MAXSIZE];

int top;

};

typedef struct stack STACK;

STACK s;

/* Function declaration/Prototype*/

void push (void);

int pop(void);

void display (void);

void main ()

{

int choice;

int option = 1;

clrscr ();

s.top = -1;

printf ("STACK OPERATION\n");

while (option)

{

printf ("--------------\n");

printf (" 1 -> PUSH \n");

printf (" 2 -> POP \n");

printf (" 3 -> DISPLAY \n");

printf (" 4 -> EXIT \n");

printf ("--------------\n");

printf ("Enter your choice\n");

scanf ("%d", &choice);

switch (choice)

{

case 1: push();

break;

case 2: pop();

break;

case 3: display();

break;

case 4: return;

}

fflush (stdin);

printf ("Do you want to continue(Type 0 or 1)?\n");

scanf ("%d", &option);

}

}

/*Function to add an element to the stack*/

void push ()

{

int num;

if (s.top -1)

{

printf ("Stack is empty\n");

return;

}

else

{

printf ("\nThe status of the stack is\n");

for (i = s.top; i >= 0; i-)

{

printf ("%d\n", s.stk[i]);

}

}

printf ("\n");

}

by

ankit shukla

Program to find the occurrences of a given character in a string in c plus plus?

#include

#include

size_t count_char (const std::string& s, const char c)

{

size_t count = 0;

size_t offset = 0;

while ((offset = s.find(c, offset)) != s.npos)

{

++count;

++offset;

}

return count;

}

int main()

{

std::string str {"Hello world!"};

std::cout << "String: "" << str << """ << std::endl;

for (auto c : str )

{

size_t count = count_char (str, c);

std::cout << "'" << c << "' occurs " << count << " time" << (count==1?"":"s") << "." << std::endl;

}

}

Example output:

String: "Hello world!"

'H' occurs 1 time.

'e' occurs 1 time.

'l' occurs 3 times.

'l' occurs 3 times.

'o' occurs 2 times.

' ' occurs 1 time.

'w' occurs 1 time.

'o' occurs 2 times.

'r' occurs 1 time.

'l' occurs 3 times.

'd' occurs 1 time.

'!' occurs 1 time.

Real world is full of classes explain?

In the real world, we humans like to classify everything from living things to inanimate objects, grouping things by the properties they share. For instance, in the world of living things we classify everything by kingdom, phylum, class, infraclass, order, suborder, family, subfamily, tribe, subtribe, genus and species. Thus the homo sapiens species belongs to the kingdom of animals, the phylum of chordata, the class of mammals, the order of primates, the family of hominidae, the tribe of hominini and the genus homo. Each classification is a more specialised type than the one that precedes it. Thus higher classes are more generic and lower classes more specific. The bat, which is also in the class of mammals, shares the same phylum and kingdom as we do, but differs in its order, family, tribe and genus. Thus we are related to bats in as much as we are both a type of mammal.

This type of classification is known as a taxonomy, and can be represented as a hierarchy, a family tree structure, with the most generic class at the top, or root, and the more specialised types splitting off on each subsequent level.

Just as we classify objects in the real world, we classify objects in the virtual world using a virtual taxonomy. The virtual taxonomy need not accurately reflect any real world taxonomy of the objects we are representing. If we wished to model a dog kennel, then we can limit the taxonomy to the genus: canis. If we also wished to identify the individual species and breed of dog then we might include those more specialised classifications, or we may limit our classification to breed. The point is we need only include those aspects that are actually of relevance to our program. For instance, we don't really need to know that a dog is actually a class of mammal unless we wished to segregate mammals from other classes, such as reptiles, but group them as animals.

By organising objects in this manner, we can greatly reduce the amount of duplicate code we need to write simply by encapsulating the generic functionality within the upper base classes, and placing the more specific functionality within the lower derived classes. For instance, most animals make some sort of noise, thus every animal object can "speak". When we call that method upon a dog, we would expect it to bark, while a cat should meow. These are simply specialised methods of a common, generic method. Animals that don't make a noise can simply default to the generic animal method, which simply produces no sound. Thus we need only cater for those that do make a sound.

What does the capacity vector member function return and how should this be used?

The vector::capacity member function returns the capacity of the storage space currently allocated to the vector, in terms of elements. The capacity is not necessarily the same as the size of the vector, but it will always be equal to or greater than the size. You can specify the capacity by using the vector::reserve member function. Reserving space for elements allows the vector to insert new elements into the vector without the need to reallocate. However, the vector automatically reallocates whenever you add more elements than the current capacity allows, and may increase the capacity beyond the new size. To optimise the capacity at any time, use the vector::shrink_to_fit member function.

The following code demonstrates how size and capacity relate to each other:

#include

#include

std::ostream& operator<< (std::ostream& os, const std::vector& v)

{

os<<"Size:\t\t"<

"\nCapacity:\t"<

std::endl;

return(os);

}

int main()

{

std::cout<<"Initialising\n"<

std::vector v;

std::cout<

std::cout<<"Insert 1 element\n"<

v.push_back(0);

std::cout<

std::cout<<"Insert 99 elements\n"<

for(size_t i=1; i<100; ++i)

v.push_back(i);

std::cout<

std::cout<<"Reserve space for 200 elements\n"<

v.reserve(200);

std::cout<

std::cout<<"Extract last 50 elements\n"<

for(size_t i=0; i<50; ++i)

v.pop_back();

std::cout<

std::cout<<"Resize to 25 elements\n"<

v.resize(25);

std::cout<

std::cout<<"Optimise\n"<

v.shrink_to_fit();

std::cout<

}

Output

Initialising

Size: 0

Capacity: 0

Insert 1 element

Size: 1

Capacity: 1

Insert 99 elements

Size: 100

Capacity: 141

Reserve space for 200 elements

Size: 100

Capacity: 200

Extract last 50 elements

Size: 50

Capacity: 200

Resize to 25 elements

Size: 25

Capacity: 200

Optimise

Size: 25

Capacity: 25

Definition of class in c plus plus?

A constructor is a function defined in a class with the name same as the class name and is used to automatically initialized the class data members. It is never preceded by a return type not even void.

eg -

class abc

{

int a, b;

abc() //constructor

{

a=0;

b=0;

}

};

main()

{

abc a;

}

The time we create object of the class in the main function the data members of the class are automatically initialised.

Constructor can even take parameter. Those constructor are known as parameterised constructor.

Java program that will input 10 scores and output the highest and lowest score?

import javax.swing.JOptionPane; //marlonroxas

public class loop_exer2

{

public static void main(String agrs[])

{

String input;

int trial=10, sc=0, h=0, l=0, test=0;

System.out.print("Scores: ");

for (int ctr=1;ctr<=10;ctr++)

{

input=JOptionPane.showInputDialog("Enter the Scores ["+trial+"] trials ");

sc=Integer.valueOf(input);

System.out.print(sc+", ");

if(test==0){h=sc;l=sc;test=1;}

if(sc>h){h=sc;}

else if(sc<l){l=sc;}

}JOptionPane.showMessageDialog(null, "Highest Score is: "+h+

"\n\nLowest Score is: "+l);

System.out.println();

System.out.println("Highest Score: "+h);

System.out.println("Lowest Score: "+l);

}

}

Perform addition multiplication subtraction of 2-D array using Operator Overloading in C plus plus?

#include<iostream>

#include<vector>

#include<random>

template<const size_t R, const size_t C>

class Matrix

{

public:

using row_type = int[C];

private: // attributes

int m_data[R][C];

public: // construction/assignment

Matrix ();

Matrix (const Matrix& source);

Matrix (Matrix&& source);

Matrix& operator= (const Matrix<R,C>& source);

Matrix& operator= (Matrix<R,C>&& source);

~Matrix () {}

public: // accessors

row_type& row (const size_t index) { return m_data[index]; }

const row_type& row (const size_t index) const { return m_data[index]; }

row_type& operator[] (const size_t index) { return m_data[index]; }

const row_type& operator[] (const size_t index) const { return m_data[index]; }

size_t size() const { return R * C; }

size_t rows() const { return R; }

size_t cols() const { return C; }

public: // operations

Matrix<R,C>& operator+= (const Matrix<R,C>&);

Matrix<R,C>& operator-= (const Matrix<R,C>&);

};

template<const size_t R, const size_t C>

Matrix<R,C>::Matrix()

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] = 0;

}

template<const size_t R, const size_t C>

Matrix<R,C>::Matrix(const Matrix<R,C>& source)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] = source.m_data[row][col];

}

template<const size_t R, const size_t C>

Matrix<R,C>::Matrix(Matrix<R,C>&& source)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] = std::move (source.m_data[row][col]);

}

template<const size_t R, const size_t C>

Matrix<R,C>& Matrix<R,C>::operator= (const Matrix<R,C>& source)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] = source.m_data[row][col];

return *this;

}

template<const size_t R, const size_t C>

Matrix<R,C>& Matrix<R,C>::operator= (Matrix<R,C>&& source)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] = std::move (source.m_data[row][col]);

return *this;

}

template<const size_t R, const size_t C>

Matrix<R,C>& Matrix<R,C>::operator+= (const Matrix<R,C>& rhs)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] += rhs.m_data[row][col];

return *this;

}

template<const size_t R, const size_t C>

Matrix<R,C>& Matrix<R,C>::operator-= (const Matrix<R,C>& rhs)

{

for (size_t row=0; row<R; ++row)

for (size_t col=0; col<C; ++col)

m_data[row][col] -= rhs.m_data[row][col];

return *this;

}

template<const size_t R, const size_t C>

Matrix<R,C> operator+ (const Matrix<R,C>& lhs, const Matrix<R,C>& rhs)

{

Matrix<R,C> sum (lhs);

return sum += rhs;

}

template<const size_t R, const size_t C>

Matrix<R,C> operator- (const Matrix<R,C>& lhs, const Matrix<R,C>& rhs)

{

Matrix<R,C> sub (lhs);

return sub -= rhs;

}

template<const size_t R, const size_t C, const size_t R1, const size_t C1>

Matrix<R,C1> operator* (const Matrix<R,C>& lhs, const Matrix<R1,C1>& rhs)

{

static_assert (C==R1, "Matrix dimension mismatch!");

Matrix<R,C1> mul;

for (size_t x=0; x!=R; ++x)

{

for (size_t y=0; y!=C1; ++y)

{

int prod = 0;

for (size_t z=0; z!=C; ++z)

{

prod += lhs[x][z] * rhs[z][y];

}

mul[x][y] = prod;

}

}

return mul;

}

template<const size_t R, const size_t C>

std::ostream& operator<< (std::ostream& os, const Matrix<R,C>& m)

{

for (size_t row=0; row<R; ++row)

{

for (size_t col=0; col<C; ++col)

{

std::cout << m[row][col] << '\t';

}

std::cout << std::endl;

}

return os;

}

int main()

{

std::default_random_engine generator;

std::uniform_int_distribution<int> distribution (1,9);

const size_t rows = 2;

const size_t cols = 3;

Matrix<rows, cols> a, b;

for (size_t row=0; row<rows; ++row)

{

for (size_t col=0; col<cols; ++col)

{

a[row][col] = distribution (generator);

b[row][col] = distribution (generator);

}

}

std::cout << "Matrix a:\n\n" << a << '\n' << std::endl;

std::cout << "Matrix b:\n\n" << b << '\n' << std::endl;

std::cout << "Matrix a + b:\n\n" << a + b << '\n' << std::endl;

std::cout << "Matrix a - b:\n\n" << a - b << '\n' << std::endl;

Matrix<cols, rows> c;

for (size_t row=0; row<rows; ++row)

{

for (size_t col=0; col<cols; ++col)

{

c[col][row] = distribution (generator);

}

}

std::cout << "Matrix c:\n\n" << c << '\n' << std::endl;

std::cout << "Matrix a * c:\n\n" << a * c << '\n' << std::endl;

}

What are C Plus Plus stream classes?

A stream class is a class that encapsulates a character buffer and allows simple insertion or extraction of character sequences from or to the buffer. A character sequence may be a single character or a string of characters. The stream may be associated with a device such as a keyboard (for extraction), a display (for insertion), a storage device such as a disk file (for either extraction or insertion, or both), or some other device that can process character sequences. The stringstream class has no device associated with it; it merely provides a character buffer for insertion or extraction from memory.

Any object that can be converted to a character sequence can be inserted into an output stream object, either by using the object's insertion operator (<<) or via one of the put() member methods associated with the stream. The standard library's output stream insertion operators provide overloads for all the built-in data types; char, int, float, double and pointer types, including all their modified types (signed, unsigned, long and short) as well as their aliases such as size_t. All the standard library <string> types are supported by all standard library streams, as are C-style strings. The insertion operator can also be overloaded to cater for all user-defined types that require it. C-style arrays and STL containers are not supported, however you can manually iterate through a sequence and insert the individual elements in an output stream, provided those element types have an appropriate insertion operator overload associated with them.

Character sequences can be extracted from an input stream using the stream's extraction operator (>>). As with output streams, the extraction operator is overloaded to cater for all built-in types, C-style strings and <string> types and can be overloaded to cater for user-defined types. When extracting a character sequence, all whitespace characters are ignored but are used to delimit each individual sequence. The stream's get() methods can be used to extract strings of arbitrary length (including whitespace) as well as use delimiters other than whitespace.

Never assume that a numeric value extracted from a stream can be converted to a valid value. Always extract to a string first, then perform the conversion to a numeric value. A common technique is to extract a string from the stream, then insert the string into a temporary stringstream object and finally extract from the stringstream to the numeric type. If the final extraction fails then the input string was not numeric. The stringstream will evaluate false (its fail bit will be set) but the original stream remains valid because extracting a string (even an empty string) is always a valid operation.

Both input and output streams use bit flags to determine their state. For instance, if you attempt to extract beyond the end of a stream associated with an input file, the eof bit is set. Note that reading the final sequence does not set the bit -- it is only set when you attempt to read another (non-existent) sequence. When a stream is used in a boolean expression, these flags are used to determine how the object is evaluated. If no flags are set, the object evaluates true, meaning the object is still in a valid state. If the return value is false, you can test individual flags to determine the state.

The following code snippet demonstrates both insertion and extraction from the standard I/O streams plus how to test for the successful extraction of an integer from the standard input stream (typically the keyboard) using a temporary stringstream:

int enter_integer (const std::string& prompt)

{

int i;

for (;;) // Forever loop -- repeat until input is successful.

{

// Temporary variables (on each iteration, these variables are created anew).

std::string input;

std::stringstream ss;

// Insert the given prompt to the standard output device.

std::cout << prompt;

// Extract input from the standard input device.

if (!(std::cin >> input))

{

// Input shouldn't fail, but if it does there's nothing we can do about it.

// Let the caller deal with it. See note below.

throw std::exception ("Unable to read from std::cin");

}

// Insert the temporary input string into the temporary stringstream object.

ss << input;

// Attempt extraction to an integer (returns true if successful)

if (ss >> i)

{

break; // Extraction successful, exit the loop.

}

// Extraction failed.

std::cerr << "Invalid input. Please re-enter.\n";

// The temporaries will fall from scope at this point,

// taking the bad input with them. The input stream

// remains valid for the next iteration.

}

return i;

}

Note: throwing an exception is never a good thing, but in this case it is the best option. If the exception is thrown, it means there's something seriously wrong with std::cin. Since that could affect the entire program, the best place to deal with this is in the program's main function, which should include a catch-all exception handler to handle any and all unhandled exceptions.

int main()

{

int num;

try

{

num = enter_integer ("Enter an integer: ");

}

catch (std::exception& e)

{

// Perform any necessary cleanup and log the error.

std::cerr << e.what() << std::endl;

return -1;

}

catch (...)

{

// Perform any necessary cleanup and log the error.

std::cerr << "An unknown exception occurred." << std::endl;

return -1;

}

// use num...

return 0;

}

What are the applications of polymorphism in c plus plus?

Polymorphism allows an object to assume different identities and behavior at run time. However, these objects should share similar features and inherit from a basic abstract object.

For example, we have a variety of graphics objects that are capable of drawing themselves, such as Circle, Triangle, Square, Rectangle and other shapes. A basic graphics object assumes the top of the inheritance hierarchy. Derived objects are the Circle, Triangle, Square, etc. The basic object supports a method called "Draw()" that allows it to draw itself on the screen. How this method is implemented is dependent on the actual object itself. Each derived object of the basic graphics object will have its unique implementation of Draw().


C++ has a feature called "dynamic binding" that implements polymorphism. Through dynamic binding, the appropriate virtual method() of Draw() is bound to the appropriate graphics object at run time.


A real world application such as a graphics editor maintains a container of objects that the user constructs at run time. Each of these objects is required to redraw itself on the screen when the screen refreshes and updates itself. Through polymorphism, the container of objects may iterate over itself and allow each object that it contains to dynamically draw itself at run time.


Sample code at compile time:


for (i=0; objects[i]; i++)
objects[i]->draw();


At run time, objects[0] = Circle, objects[1] = Square, objects[2] = Polygon, etc.
The behavior of the program at objects[i]->draw() is undefined until run time.


Other applications that utilize the feature of polymorphism includes:

  • providing to customers flight information from a variety of airlines, each airline abiding by a common set of API to access its flight information
  • providing to customers pricing information of parts from a variety of brands and manufacturers
  • providing to customers menu information from different restaurants in the area
  • any application that requires supplying to customers a common API (user interface) to access a multitude of databases (flight information, scheduling, food vendors, pricing information, etc.)

How do you avoid garbage values in c plus plus programs?

Initialization. Hint: your compiler might warn you, neverignore warnings if you aren't absolutely sure what they mean.

What is meant by cascading in c plus plus?

Cascading refers to the following style of calling multiple methods in a sequence:

someObject.firstMethod().secondMethod().thirdMethod();

For this to work, firstMethod() returns an object on which secondMethod() is called, and similarly this returns an object on which thirdMethod() is called.

A commonly seen instance of this is the overloaded stream insertion operator - i.e. operator<<() - in the standard library. For example, you can write:

std::cout << "The meaning of life is " << 42 << std::endl;

Each invocation of operator<<() returns the std::cout object, allowing an arbitrarily long sequence of calls to be chained together.

Here's an example of a class which supports such cascading:

class MyClass {private:int data;

public:MyClass(int initData) : data(initData) {}

MyClass goUp() {data++;return *this;}

MyClass goDown() {data--;return *this;} };

With the above definition, we can write

MyClass obj;

obj.goUp().goUp().goDown();

and so on.

What is a statement used to open data file in c plus plus?

FILE* fopen(<filename>, <mode>);

E.g.,

FILE* f = fopen("C:\\Users\\<user_name>\\My Documents\\data_file.dat", "rb");

Opens the specified file for reading ("r") in binary mode ("b").

What is member fusion in c plus plus?

If you are asking about member functions.

When we declare a function inside a class then that function becomes member function of that class and this function can access the whole class

C plus plus program that display an employees name by entering an id?

Ideally you'd want to use a DBMS to store and retrieve the employee data, but we'll keep it simple and use some static data instead.

#include

#include

#include

#include

struct employee

{

std::string m_name;

unsigned m_id;

employee(std::string name, unsigned id): m_name(name), m_id(id) {}

};

std::vector employees;

void load_data ()

{

employees.push_back (employee ("Alan", 1));

employees.push_back (employee ("Brian", 2));

employees.push_back (employee ("Charles", 3));

employees.push_back (employee ("David", 4));

employees.push_back (employee ("Eric", 5));

}

unsigned input_id (std::string prompt)

{

unsigned id = 0;

while (1)

{

std::cout<

std::string input="";

getline (std::cin, input);

std::stringstream ss (input);

if (ss>>id)

break;

std::cout<<"Invalid input.\n";

}

return (id);

}

employee* locate (unsigned id)

{

for (unsigned i=0; i

{

if (employees[i].m_id == id)

return (&employees[i]);

}

return (NULL);

}

int main()

{

load_data ();

unsigned id=0;

do

{

if( id=input_id("Enter an employee ID (0 to exit)"))

{

if (employee* emp = locate( id ))

std::cout<m_name<<'\n'<

else

std::cout<<"There is no employee with that ID.\n"<

}

} while( id );

std::cout<

}

Example output

Enter an employee ID (0 to exit): 6

There is no employee with that ID.

Enter an employee ID (0 to exit): 5

Eric

Enter an employee ID (0 to exit): 2

Brian

Enter an employee ID (0 to exit): 0