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

Code written in a specific format to perform a single task or calculation is called a?

It's called a statement. However, C++ permits many tasks and calculations to be performed with a single statement. Good class design ensures that all the individual processes behind a statement are completely hidden from the caller, thus ensuring clean and clear code that is easily understood.

Is x plus equals y is post increment or pre increment?

The '+=' operator behaves like a pre increment operator.

Use some methods of a class in subclass without inheritance in c plus plus?

You can't have a subclass without inheritance. A subclass is just another name for a derived class, and derived classes inherit all the public and protected members of their base classes. You cannot have a base class with neither public nor protected members -- there has to be at least one exposed interface, even if it is only a static public method.

I suspect you are actually asking how to call a specific method of a derived class when all you have is a pointer to its base class. The correct solution is to use inheritance and call a virtual method of the base class. But what do you do when the specific method you want to call is non-generic?

This is a classic case of poor class design. The problem is not that you are trying to extort non-generic behaviour from a base class, the problem is in how you are going about it. If you only have a pointer or reference to the base class then you are expected to make use of its generic interface. If you need a more specific interface, then you need a pointer or reference to the more specific type, not its generic type. Unfortunately, this may not always be possible, especially when dealing with legacy code for which you have no control over. In these cases, the only solution is to resort to expensive runtime type information and dynamically cast your base class pointer to the appropriate type. If the return value is NULL then the base class does not point at your expected derivative, so you must check the return value is non-NULL before calling the specific method. This is the only safe way of doing it, in the absence of a suitable generic interface.

This, in turn, means your calling code requires knowledge of that specific type. While that's generally not a problem when the calling code is external to the base class, it is a problem when the calling code is the base class itself. This means your base class must be blessed with knowledge about some or all of its derivatives. To be blunt, that's a maintenance nightmare because every time you derive a new object for which you wish to extort specific behaviour you must also update the base class in order to accommodate that new derivative. Quite simply this is a sloppy way of going about things.

The best solution is, of course, to rethink your design. Separate your interfaces from your implementations and gather all the common interfaces together in the base class itself. Look into ways of generalising the more specific methods such that it is possible to call those methods from the generic interface, without the need for runtime type information. Use arguments as flags to allow greater flexibility, and let the more specific implementations work out for themselves exactly which calls to make based upon those arguments. You cannot avoid using inheritance, of course, but ultimately it is the correct way of doing things. Your code will be cleaner and easier to maintain in the long run. And it all starts with good design.

Write a program to swap 2 variables with out using 3rd variable through cout?

#include <iostream>

using namespace std;

int main()

{

int a, b;

cin >> a;

cin >> b;

a = a * b;

b = a / b;

a = a / b;

cout << a << " " << b;

char wait;

cin >> wait;

return 0;

}

What makes for a good or bad variable name in C plus plus programming languages?

A good variable name is one that is clear, related to the data it stores. Also, you should try to avoid confusions with other variables.

What is passing by address in C code?

When you pass in a memory address (ie. pointer) into a function rather than passing in the value itself.

Write a program in cpp to print the charminar?

int main (void) { puts ("charminar"); return 0; }

Visual c plus plus 6.0 free installer?

Visual C++ 6.0 is more than 16 years old. It is no longer available to buy and it was never available for free. The current version is Visual C++ 2013.

Write a cpp program to convert entered date into words?

#include<iostream>

#include<sstream>

#include<chrono>

#include<ctime>

std::string months[12] { "January", "February", "March", "April", "May", "June", "July",

"August", "September", "October", "November", "December"};

class date

{

public:

date (std::string = "");

date (size_t dd, size_t mm, size_t yyyy);

date (const date& dt): d{dt.d}, m{dt.m}, y{dt.y} {}

date (date&& dt): d{dt.d}, m{dt.m}, y{dt.y} {}

date& operator= (const date& dt) { d = {dt.d}, m = {dt.m}, y = {dt.y}; return *this; }

date& operator= (date&& dt) { d = {dt.d}, m = {dt.m}, y = {dt.y}; return *this; }

static bool is_leap_year (size_t year);

static date today ();

static bool validate (size_t dd, size_t mm, size_t& yyyy);

size_t day() const { return d; }

size_t month() const { return m; }

size_t year() const { return y; }

operator std::string () const;

private:

size_t d;

size_t m;

size_t y;

};

bool date::is_leap_year (size_t year)

{

if (!(year%4)) return false;

if (!(year%100)) return true;

if (!(year%400)) return false;

return true;

}

date date::today()

{

time_t tt = time (nullptr);

struct tm *tm = localtime (&tt);

return date (tm->tm_mday, tm->tm_mon+1, tm->tm_year+1900);

}

bool date::validate (size_t dd, size_t mm, size_t& yyyy)

{

// There was no year zero!

if (!yyyy)

return false;

// There is no day zero!

if (!dd)

return false;

// Check day and month combinations.

switch (mm)

{

case 2:

if (dd > 29 (dd > 28 && !date::is_leap_year (yyyy)))

return false;

break;

case 1: case 3: case 5: case 7: case 8: case 10: case 12:

if (dd > 31)

return false;

break;

case 4: case 6: case 9: case 11:

if (dd > 30)

return false;

break;

default:

return false;

}

// 10 dates were skipped during the switch from Julian to Gregorian

if (yyyy==1582 && mm==10 && dd>4 && dd<15)

return false;

// The date is valid!

return true;

}

date::date (size_t dd, size_t mm, size_t yyyy): d {dd}, m {mm}, y {yyyy}

{

if (!validate (dd, mm, yyyy))

throw std::range_error ("date (size_t,size_t,size_t) - invalid date values!");

}

date::date (std::string ddmmyyyy)

{

if (!ddmmyyyy.size())

{

date dd (today());

d = dd.d;

m = dd.m;

y = dd.y;

return;

}

const std::string error {"date(std::string) - invalid argument!"};

const std::string valid {"0123456789\"};

// check for invalid characters

if (ddmmyyyy.find_first_not_of (valid) != ddmmyyyy.npos)

throw std::range_error (error);

// locate first slash

size_t s1 = ddmmyyyy.find('\\');

if (!s1 s1 ddmmyyyy.npos)

throw std::range_error (error);

// ensure no more slashes

size_t s3 = ddmmyyyy.find ('\\', s2+1);

if (s3 != ddmmyyyy.npos)

throw std::range_error (error);

// parse string

std::string sd = ddmmyyyy.substr (0, s1);

std::string sm = ddmmyyyy.substr (s1+1, s2-s1-1);

std::string sy = ddmmyyyy.substr (s2+1, ddmmyyyy.size()-s2);

std::stringstream ss;

ss << sd << " " << sm << " " << sy;

size_t dd, mm, yyyy;

ss >> dd;

ss >> mm;

ss >> yyyy;

if (!validate(dd,mm,yyyy))

throw std::range_error (error);

d = dd;

m = mm;

y = yyyy;

}

date::operator std::string () const

{

std::stringstream ss;

ss << d << '\\' << m << '\\' << y;

return ss.str();

}

int main()

{

date d;

std::string input;

while (true)

{

std::cout << "Enter a date (dd\\mm\\yyyy): ";

std::cin >> input;

try

{

date t {input};

d = t;

break;

}

catch (std::range_error& e)

{

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

}

}

std::cout << "Date: " << d.day();

switch (d.day() % 10)

{

case (1): std::cout << "st"; break;

case (2): std::cout << "nd"; break;

case (3): std::cout << "rd"; break;

default: std::cout << "th"; break;

}

std::cout << " " << months[d.month()-1] << ", " << d.year() << std::endl;

}

Why is it important to check the return status when opening a file in c plus plus?

The return value tells you if any errors occurred. A value of 0 typically indicates no error.

How much was CPP Limited fined?

The Card Protection Plan Limited firm was reported to have been fined about 10 million pounds. The fine was a result of the firm selling useless insurances to its clients.

Why c is called partially an OOP language?

C is not an OOP language, period. However, while C++ supports OOP it does not rely on it. With C++, you can mix procedural, structured and object-oriented principals by mixing C++ code with C-style code and even raw assembly routines, neither of which are object-oriented.

Write a program to demonstrate the catching of all exceptions what happens when a raised exception is not caught by catch block in the absence of a catch all exception block?

If an exception is not caught then your program has undefined behaviour. Ultimately the program crashes, but since you haven't handled the exception you've no way of knowing what damage has been done. Files could be wiped or currupted, planes could fall from the sky... anything is possible with undefined behavour.

The best way to deal with unknown exceptions is to first catch them with a catch-all. However, you cannot actually handle the exception unless you know what type of exception you are actually dealing with. Thus the normal course of action is to assume the worst, perform any and all necessary cleanup, log the exception as an unknown exception and rethrow. As the exception percolates back down the call stack, all other exception handlers should do the same: cleanup, log and rethrow. If you're lucky, another handler might recognise the exception and be able to provide more detailed information on the type of exception. Ultimately you must never allow a program to continue executing if you cannot handle an exception.

C++11 offers a more elegant solution using a nested try catch within a catch-all. However, it makes more sense to place the nested try catch in a global function (e.g., handle_eptr()) which can specifically deal with all catch-all exceptions. Like so...

#include <iostream>

#include <string>

#include <exception>

#include <stdexcept>

void handle_eptr(std::exception_ptr eptr)

{

try

{

if (eptr) std::rethrow_exception (eptr);

}

catch (const std::exception& e)

{

std::cerr << "Exception: "" << e.what() << ""\n";

}

}

int main()

{

try

{

std::string().at(1); // throws "invalid string position"

}

catch(...) // catch-all

{

// perform any necessary cleanup here before calling the global handler

handle_eptr (std::current_exception());

}

}

Output:

Exception: "invalid string position"

Note that handle_eptr() receives a std::exception_ptr. By itself this is useless, but std::rethrow_exception() converts the eptr to a standard exception which can then be thrown, caught and logged. You must still perform any necessary cleanup and allow the program to terminate gracefully, but at least you now know what type of exception you are dealing with and can provide a specific handler to handle it.

Note that handle_eptr() should be fleshed out to accept all necessary debug information such as the filename and the line number from the catch_all that called it. The example merely demonstrates how to pass the eptr and convert it into an actual exception.

What is the difference between implicit and explicit call of constructor in c plus plus?

An implicit constructor call will always call the default constructor, whereas explicit constructor calls allow to chose the best constructor and passing of arguments into the constructor.

What is the usage of union in CPP?

A union in C or C++ is like a structure, except that each element in the structure starts at the same memory address. It is useful for storing more than one type of data, but only one at a time, in the same memory location.

It can also be used for the potentially unsafe technique of looking at the bit patterns of one data type using another data type. (It is unsafe because internal memory organization of bits and bytes is an implementation specific thing, and depending on one particular organization can lead to incorrect program behavior.)

Four components of capital structure?

the components of capital structure(CS) includes:

1. CS with equity sahres only.

2. CS with equity and preference shares.

3. CS with equity and debentures.

4. CS with equity shares, preference shares and debentures.

How do you write a c plus plus program to print a hollow square of a given size using asterisks and blanks?

void draw_box (const unsigned size)

{

if (!size) return; // size must be non-zero!

const char star {'*'}; // asterisk

const char nl {'\n'}; // newline

if (size==1)

{

// a box of size 1 is just a single asterisk

std::cout << star << nl;

return;

}

// else if (1 < size) ...

// the top and bottom lines are the same

const std::string line (size, star);

// hollow line (spaces)

const std::string hollow (size-2, ' ');

// draw the top line

std::cout << line << nl;

// draw the middle lines (if size>2)

for (unsigned i=2; i<size; ++i)

std::cout << star << hollow << star << nl;

// draw the bottom line

std::cout << line << nl;

}

What is the main purpose in using a destructor?

Destructors are called automatically whenever an object falls from scope. Even if you don't actually declare a destructor, one is implied.

The primary purpose of a destructor is to give the programmer one final chance to clean up an object's memory allocations before the object is destroyed forever. If an object has allocated memory associated with it (via member pointer variables), then that memory must be released before the object is destroyed, otherwise a memory leak is inevitable.

Destructors are also important in class inheritance. When a derived object falls from scope, its immediate base class destructors are called, followed by their base class destructors. This is effectively the reverse of an object's construction, which always begins with the least-derived base classes, working up to the most-derived class, which is the object itself. Just as a derived class cannot be instantiated until all its base classes are constructed, a base class object cannot be destroyed until all its derived class objects are destroyed. All the destructors in a class hierarchy must be declared virtual to ensure the correct most-derived destructor is called whenever a base class reference falls from scope.

How do I read a memory address with borland c?

In order to read a memory address you must hold a reference to that address. If the object at that address is a named object, then the object's name is a reference, thus we can simply take its address using the address-of operator (unary &):

int i = 42;

printf ("Variable i resides at memory address 0x%x\n", &i);

If we wish to store the address we must use a pointer variable of the appropriate type:

int* p = %i;

Like any other variable, a pointer variable has an address of its own, thus we can read its address:

printf ("Variable p resides at memory address 0x%x\n", &p);

To read the address being pointed at we simply examine the pointer's value:

printf ("Variable p refers to memory address 0x%x\n", p);

Note this address is the same as the address of i, the object being referred to (pointed at).

To read the value stored at the address being pointed at we must dereference the pointer (unary *). Dereferencing is also known as indirection because we are indirectly accessing the object's value:

printf ("Variable p refers to the value %d\n", *p); // e.g., 42

Pointers can refer to both named and anonymous objects. Anonymous objects are simply objects allocated on the heap at runtime. Since they don't exist at compile time we cannot name them:

int* anon = malloc (sizeof (int)); // allocate memory

Note that anon is the name of the pointer, not the object being pointed at.

printf ("The anonymous variable resides at memory address 0x%x\n", anon);

free (anon); // always release heap allocations as soon as we are finished with them!

Pointers also make it possible to pass memory addresses to and from functions (also known as pass by reference):

void f (int* p) {

}

int a = 42;

f (&a); // pass the address of a to the f() function

Note that all variables in C are passed by value, but when we pass a pointer by value we are passing an address and an address is a reference. Passing references is useful when the object being referred to cannot be efficiently passed by value. Typically this means any value that is larger than the word value of the underlying architecture (e.g., 4 bytes on a 32-bit system). Arrays in particular are never passed by value, hence an array implicitly converts to a pointer.

A program to find sum of digits repeatedly until a single digit is obtained?

#include<stdio.h>

#include<conio.h>

main()

{

int n,s=0,sum=0,i,d;

printf("enter the number");

scanf("%d",&n);

while(n>0)

{

d=n%10;

s=s+d;

n=n/10;

}

while(s>0)

{

i=s%10;

sum=sum+i;

s=s/10;

}

printf("%d",sum);

getch();

}

How do you save GIF extension file in Dev c plus plus?

The extension is actually immaterial. It merely serves to give the operating system a hint as to the file's content, allowing the file to be associated with a particular application, such as a GIF file viewer or an image editor application. In order to save a GIF file, you must first re-encode the image (assuming it is not already in GIF format), and save the output to a file with a GIF extension.