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

What is Information Hiding in OOP?

There is no such concept as information hiding in OOP. While many programmers incorrectly believe private and protected member variables are hidden in a class, these access specifiers do nothing more than limit access to those variables, they do not actually hide anything. Information hiding is actually a function of binary executables and libraries, not OOP, because information can be obfuscated by procedural machine code far more easily than with structured source code.

When referring to OOP, we use the term abstraction rather than information hiding. Abstraction relates to the way in which it is not necessary to know the underlying storage mechanism of a class, nor its implementation details, in order to make use of a class. This allows the class designer to alter the class design specification without affecting the existing consumers, provided the existing abstract interface remains unaltered. In other words, it reduces maintenance by localising changes within the class, rather than affecting code outside of the class as would occur in a non-OOP environment. It is the interface which provides the abstraction, but it does not physically hide anything. That is, while it is not necessary to know the underlying storage or implementation details of the class, there is absolutely nothing to prevent you from looking at those details, even if those details are obfuscated within a binary library (just because something is hidden doesn't mean it can't be found with a bit of effort).

What are various types of data conversion that can not be handled by compiler?

Data conversion which culminate in loss of data will usually lead to the generation of warning messages.

Eg: from float to int.

These conversions should be explicit.

Also conversion between two different objects is only possible if there is a function specifying the conversion method.

Write C coding for swamping the values of two variables without using a third variable?

I'll assume you meant to say: Swapping instead of Swamping.

You would need to perform the XorSwap algorithm:

void XorSwap(int *x, int *y) {

if(x != y) {

*x ^= *y;

*y ^= *x;

*x ^= *y;

}

}

You can read more about this algorithm on Wikipedia.

How do you call a member function of one class in another class using friend function?

class B; // forward declaration.

class A

{

private:

void myFunction(B b){b.myFunction();} // Calls private method in b.

};

class B

{

friend void A::myFunction(B b); // Friend function declaration.

private:

void MyFunction();

};

What are commonly use libraries of c plus plus function arrays?

Function arrays are nothing more than arrays of function pointers so, besides the stddef header, you don't really need any libraries to implement a function array unless those functions use a type that isn't available in stddef.

#include<stddef.h>

void func_1() {} // obviously you must provide

void func_2() {} // implementations for these

void func_3() {} // functions

// a function array

void (*function_array[])() = { func_1, func_2, func_3 };

int main()

{

for(unsigned i=0; i<3; ++i)

function_array[i]; // call the function

}

How can you display system tray icon using visual c plus plus?

You add an icon to the system tray by invoking the Shell_NotifyIcon function. This function can be found in the Shell32.dll dynamic link library file. To make use of it, your program must include the Shellapi.h header file and link to the Shell32.lib library.

For more information, press F1 while Visual C++ is active to load the Microsoft Help Viewer (or MSDN if using an earlier version), then search for "Notifications and the Notification Area". The notification area has been known historically as the system tray or status area. Also consult the Windows User Experience Interaction Guidelines for best practices in the use of notifications.

How can you create a comment in a C plus plus program?

There are two ways:

The single line comment with a double slash //. Everything after the double slash on a single line is commented out.

The multi-line comment using a /* to open, and a */ to close.

A good IDE will color code the comments instantly.

How do you use sin in c plus plus?

#include<iostream>

int main()

{

std::cout << "sin(1) = " << std::sin(1.0) << std::endl;

std::cout << "cos(1) = " << std::cos(1.0) << std::endl;

std::cout << "tan(1) = " << std::tan(1.0) << std::endl;

std::cout << "asin(1) = " << std::asin(1.0) << std::endl;

std::cout << "acos(1) = " << std::acos(1.0) << std::endl;

std::cout << "atan(1) = " << std::atan(1.0) << std::endl;

}

Output:

sin(1) = 0.841471

cos(1) = 0.540302

tan(1) = 1.55741

asin(1) = 1.5708

acos(1) = 0

atan(1) = 0.785398

What is composite data type in c?

Composite datatypes are the datatypes which can be constructed with in a program by using prmitive datatypes and other composite types.the act of constructing a composite data type is called composition..............

C plus plus code of calendar using loop statement?

#include<iostream>

#include<iomanip>

#include<string>

#include<sstream>

#include<cassert>

using std::cout;

using std::cin;

using std::endl;

using std::setw;

using std::string;

using std::stringstream;

#ifndef NDEBUG

#define assert_year(year) do { assert (1900 <= (year)); } while(0)

#define assert_month(month) do { assert ((month) && ((month) <= 12)); } while(0)

#define assert_day(day) do { assert ((day) && ((day) <= 31)); } while(0)

#else

#define assert_year(year) ((void)0)

#define assert_month(month) ((void)0)

#define assert_day(day) ((void)0)

#endif NDEBUG

bool is_leap_year (size_t year)

{

assert_year (year);

if (year%4) return false; // If not a multiple of 4 then common year.

if (year%100) return true; // If a multiple of 4 but not of 100 then leap year.

if (year%400) return false; // If a multiple of 4 and 100 but not of 400 then common year.

return true; // If a multiple of 4, 100 and 400 then leap year.

}

size_t days_in_month (size_t month, size_t year)

{

assert_month (month);

switch (month)

{

case 2:

return is_leap_year (year) ? 28 : 29;

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

return 30;

}

return 31;

}

size_t day_of_year (size_t day, size_t month, size_t year)

{

assert_day (day);

assert_day (month);

size_t days = day;

while (--month)

days += days_in_month (month, year);

return days;

}

size_t days_in_previous_years (size_t year)

{

assert_year (year);

size_t days = 0;

while (1900 < --year)

days += is_leap_year (year) ? 366 : 365;

return days;

};

size_t days_since_epoch (size_t day, size_t month, size_t year)

{

// Epoch is 1st January 1900

return days_in_previous_years (year) + day_of_year (day, month, year) - 1;

}

size_t day_of_week (size_t day, size_t month, size_t year)

{

return days_since_epoch (day, month, year) % 7;

}

void print_calendar (size_t month, size_t year)

{

assert_month (month);

cout << endl;

switch (month)

{

case 1: cout << "January"; break;

case 2: cout << "February"; break;

case 3: cout << "March"; break;

case 4: cout << "April"; break;

case 5: cout << "May"; break;

case 6: cout << "June"; break;

case 7: cout << "July"; break;

case 8: cout << "August"; break;

case 9: cout << "September"; break;

case 10: cout << "October"; break;

case 11: cout << "November"; break;

case 12: cout << "December"; break;

}

cout << ' ' << year << endl;

cout << "\n Su Mo Tu We Th Fr Sa\n";

size_t start_day = day_of_week (1U, month, year);

size_t days = days_in_month (month, year);

size_t count = start_day % 7U + 1U;

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

cout << setw (4) << ' ';

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

{

cout << setw (4) << i;

++count;

if (count == 7)

{

cout << endl;

count = 0;

}

}

if (count)

cout << endl;

cout << endl;

}

size_t ask (string prompt)

{

for (;;)

{

cout << prompt;

string input;

cin >> input;

stringstream ss;

ss << input;

size_t reply;

if (ss >> reply)

return reply;

cout << "Invalid input.\n";

}

}

int main (void)

{

for (;;)

{

enter_month:

size_t month = ask ("Enter a month (1 - 12, 0 to exit): ");

if (!month)

break;

if (month > 12)

{

cout << "Invalid month." << endl;

goto enter_month;

}

enter_year:

size_t year = ask ("Enter a year (>= 1900, 0 to exit): ");

if (!year)

break;

if (year < 1900)

{

cout << "Invalid year." << endl;

goto enter_year;

}

print_calendar (month, year);

}

}

Enumerate the types of selection constructs in c plus plus?

Selection constructs in C++

  1. if...else
  2. switch/case
  3. conditional ternary operator (?:)

C program to accept name age and print eligible for vote or not?

#include<stdio.h>

#include<conio.h>

main()

{

int age;

printf(" enter the age ");

scanf("%d",&age);

if(age>18)

{

printf(" citizen can give vote ");

}

else

{

printf(" citizen cannot give vote");

}

return 0;

}

A program of c plus plus to accept the string and display the alternate characters in reverse order using pointer?

The following program prints every second character of the input in reverse order.

#include<iostream>

#include<sstream>

int main()

{

std::cout << "Input:\t";

std::string input = "";

std::getline (std::cin, input);

if (input.size())

{

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

unsigned index = input.size() / 2 * 2;

do

{

index -= 2;

std::cout << input[index];

} while (index);

std::cout << std::endl;

}

}

How do you write a c plus plus program to remove duplicate elements in an array using function templates?

The most efficient method is to sort the array and then remove duplicate neighbours. If you want to maintain the original order, you must do it the long way, comparing every element with every other element, removing duplicates as you go.

Both methods are shown below.

#include // std::cout and std::endl

#include // std::vector

#include // std::sort and std::unique

#include // pseudo-random numbers

#include // required to seed random numbers

template

unsigned remove_unsorted_duplicates (std::vector& arr)

{

// Maintain count of deletions.

unsigned deletions(0);

// Need at least 2 elements...

if (arr.size() < 2)

return deletions;

// Loop through all but the penultimate element (left elements).

unsigned left(0);

unsigned penultimate = arr.size() - 1;

while (left < penultimate)

{

// Loop through all elements to the right of left element (right elements).

unsigned right = left + 1;

while (right < arr.size())

{

// Duplicate?

if (arr[left] == arr[right])

{

// Left-shift all the elements from end of the array to fill the gap.

unsigned i = right;

while (i < penultimate)

{

arr[i] = arr[i+1];

++i;

}

// Remove the redundant element from the end of the array.

arr.pop_back ();

// Increment the deletion total.

++deletions;

// Decrement the penultimate count.

--penultimate;

}

else

{

// Not a duplicate -- move to next element.

++right;

}

}

// Move to next element from left.

++left;

}

// Return the number of deletions.

return deletions;

}

template

unsigned remove_sorted_duplicates (std::vector& arr)

{

unsigned size = arr.size();

std::sort (arr.begin(), arr.end());

std::vector::iterator it = std::unique (arr.begin(), arr.end());

arr.resize (std::distance (arr.begin(), it));

return size - arr.size();

}

template

void print_array (std::vector& arr)

{

for (unsigned i(0); i < arr.size(); ++i)

{

std::cout << arr[i] << ' ';

}

std::cout << std::endl;

}

int main()

{

// Pseudo-random number generator.

std::default_random_engine generator;

generator.seed ((unsigned) time (NULL));

std::uniform_int_distribution distribution (1, 5);

// Create an array with 10 random elements in the range 1 to 5.

// Guaranteed to create at least 5 duplicates.

std::vector arr (10);

for (unsigned i(0); i < arr.size(); ++i)

{

arr[i] = distribution (generator);

}

// Copy the array.

std::vector arr2 (arr);

std::cout << "Unsorted duplicate removal\n" << std::endl;

std::cout << "Before:\t";

print_array (arr);

unsigned deletions = remove_unsorted_duplicates (arr);

std::cout << "After:\t";

print_array (arr);

std::cout << "There were " << deletions << " deletions.\n" << std::endl;

std::cout << "Sorted duplicate removal\n" << std::endl;

std::cout << "Before:\t";

print_array (arr2);

deletions = remove_sorted_duplicates (arr2);

std::cout << "After:\t";

print_array (arr2);

std::cout << "There were " << deletions << " deletions.\n" << std::endl;

}

Example Output

Unsorted duplicate removal

Before: 2 2 1 3 1 3 1 4 3 2

After: 2 1 3 4

There were 6 deletions.

Sorted duplicate removal

Before: 2 2 1 3 1 3 1 4 3 2

After: 1 2 3 4

There were 6 deletions.

Tower of Hanoi C plus plus visual?

#include<iostream>

#include<string>

#include<vector>

#include<sstream>

using namespace std; // For std::cout and std::endl

// Each rod in the tower has a variable number of rings.

typedef vector<size_t> Rod;

// Displays the tower.

void display(Rod tower[], size_t move=0)

{

if(!move)

cout<<"Initial Position";

else

cout<<"Move "<<move;

cout<<":\n"<<endl;

static const char label[]="ABC";

for(size_t rod=0; rod<3; ++rod)

{

cout<<label[rod]<<":";

for(size_t ring=0; ring<tower[rod].size(); ++ring)

cout<<" "<<tower[rod][ring];

cout<<endl;

}

cout<<endl;

}

int main()

{

cout<<"Tower of Hannoi\n===============\n"<<endl;

size_t rings=1;

do

{

if( rings<1 rings>9 )

cout<<"You must enter a value in the range 1..9.\n"<<endl;

cout<<"Enter the no. of rings (1..9): ";

string input;

getline(cin, input);

stringstream(input)>>rings;

cout<<endl;

}while(rings<1 rings>9);

// Instantiate the three towers.

Rod tower[3];

// Push all the rings onto the 1st tower (largest to smallest)

// and display the initial position.

for(size_t ring=0; ring<rings; ++ring)

tower[0].push_back(rings-ring);

display(tower);

// Determine the minimum no. of moves required

// (2 raised to the power of rings, minus 1).

size_t moves=(1<<rings)-1;

// Determine if the number of rings is odd or even.

size_t odd=rings&1;

// Begin moving rings...

size_t move=0;

while(move<moves)

{

// Determine which 2 of the 3 rods to compare.

size_t rod_index1=0, rod_index2=odd?1:2;

switch(move%3)

{

case(0): rod_index2=odd?2:1; break;

case(2): rod_index1=odd?2:1; break;

}

// Reference the two rods.

Rod& rod1=tower[rod_index1];

Rod& rod2=tower[rod_index2];

// Obtain the top-most ring sizes (0 if rod is empty).

size_t ring1=rod1.size()?*rod1.rbegin():0;

size_t ring2=rod2.size()?*rod2.rbegin():0;

// Invariant: ring1 + ring2 > 0.

// Move the smallest ring to the other rod.

if(!ring2 (ring1 && ring1<ring2))

{

rod1.pop_back();

rod2.push_back(ring1);

}

else

{

rod2.pop_back();

rod1.push_back(ring2);

}

// Display the result of the move.

display(tower, ++move);

}

// Finished!

cout<<"Complete in "<<moves<<" moves!\n"<<endl;

}

Why you use header files in c?

the use of header files is to add functionality. Header files are basically saying put code in that header file here so you don't have to type that many lines of code.

How do you create a class complex in c plus plus and overload the following operators plus minus multiplication and division?

The C++ standard library provides a class complex in <complex>, including all the standard arithmetic operator overloads. It is highly unlikely that a user-defined implementation will improve upon any of the existing implementations, however the source code is worthy of study, particularly if you wish to extend the implementation in order to cater for a user-defined scalar; all the built-in scalars are already catered for.

Stack program using key word abstract in c plus plus?

There is no abstract keyword in C++, therefore what you ask cannot be done.

An abstract base class (or abstract data type if you prefer) is achieved by declaring at least one pure-virtual function in a class. Abstract base classes cannot be instantiated other than through derivation, where the pure-virtual method must be overridden by the derivative lest it become abstract itself.

The following example demonstrates an abstract data type:

struct abstract_object {

// pure-virtual function (no implementation provided)

virtual void virtual_method()=0;

};

struct real_object: public abstract_object {

// Implementation of pure-virtual function

void virtual_method(){ std::cout<<"Hello world!"<<std::endl; }

};

In the above example, abstract_object provides no implementation of the pure-virtual method. You can provide a generic implementation if you wish but it will not be inherited by any derivative (you can only call the generic method explicitly from the more specific implementation in the derived class). The fact it is declared pure-virtual guarantees that all non-abstract derivatives will provide their own specific implementations. Once a derivative implements the method, that implementation can subsequently be inherited by other derivates or overridden as required, just as if it were a non-pure-virtual method.

An abstract base class is a conceptual class. For example, circles and squares are actual objects that might be derived from a conceptual shape class. You wouldn't normally want users to be able to instantiate a shape by itself, so it must contain at least one pure-virtual method, such as a draw() method. This not only prevents users from instantiating shapes, it ensures that all derivatives, such as circle and square, provide their own specific draw methods. That is, the shape doesn't have enouygh information to draw itself, but a circle or square do. Thus the role of the conceptual class is simply in order to provide a generic interface that must be overridden by the more specific types.

To use an abstract base class in a stack implementation, you might choose to use a generic data container that the stack can easily push and pop, regardless of its actual type. The actual type of data on the stack is of no importance to the stack itself, that aspect is only of importance to the stack's consumers. By using a conceptual object with a generic interface, consumers can be assured that all derivatives of that conceptual object can safely be pushed and popped from the stack, while the generic interface methods of the conceptual object allow consumers to access the more specific behaviours of those objects, without the need to know the actual type (which requires expensive runtime type information). In other words, you can push squares and circles onto a stack of shapes, but when you pop them from the stack, you don't need runtime type information to determine their actual type, because all derivatives of shape are still shapes, they simply behave according to their actual type, polymorphically. That is, when you pop a shape off the stack and call its draw method, you rightly expect a circle to draw a circle and a square to draw a square. You get that for free because the draw method is a virtual method. And the only reason for having an abstract base class (shape) in the first place is that you don't want consumers instantiating shape objects directly, because a shape is a conceptual, generic object, not an actual object.

How do you write the programme that display truth table of AND gate by using C or C plus plus programming language?

#include <iostream>

int main (void)

{

std::cout << "\nBitwise AND (&):\n";

for (int a=0; a<=1; ++a)

for (int b=0; b<=1; ++b)

std::cout << a << " & " << b << " is " << a & b << std::endl; std::cout << "\nLogical AND (&&):\n";

for (int a=0; a<=1; ++a)

for (int b=0; b<=1; ++b)

std::cout << a << " && " << b << " is " << a && b << std::endl;

return 0;

}

Definition of comments in c plus plus?

In C++, you can write comments two different ways. The old way, which is C compatible, is to bracket the commented text with /* and */. These comment operators extend across lines. The new way, for C++, is the single line comment. You start the comment with //, and everything from that point to the end of the current line is a comment.

Note: You can use the preprocessor as well:
#if 0
Many many lines of comments
#endif